Reading JSON objects from a large file

后端 未结 3 1347
轻奢々
轻奢々 2020-12-21 19:12

I am looking for a JSON Parser that can allow me to iterate through JSON objects from a large JSON file (with size few hundreds of MBs). I tried JsonTextReader from Json.NET

3条回答
  •  温柔的废话
    2020-12-21 19:16

    Let's assume you have a json array similar to this:

    [{"text":"0"},{"text":"1"}......]
    

    I'll declare a class for the object type

    public class TempClass
    {
        public string text;
    }
    

    Now, the deserializetion part

    JsonSerializer ser = new JsonSerializer();
    ser.Converters.Add(new DummyConverter(t =>
        {
           //A callback method
            Console.WriteLine(t.text);
        }));
    
    ser.Deserialize(new JsonTextReader(new StreamReader(File.OpenRead(fName))), 
                    typeof(List));
    

    And a dummy JsonConverter class to intercept the deserialization

    public class DummyConverter : JsonConverter
    {
        Action _action = null;
        public DummyConverter(Action action)
        {
            _action = action;
        }
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(TempClass);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            serializer.Converters.Remove(this);
            T item = serializer.Deserialize(reader);
            _action( item);
            return null;
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    

提交回复
热议问题