读取JSON对象从一个大文件大文件、对象、JSON

2023-09-03 06:56:09 作者:怎敢再扰

我要寻找一个JSON解析器,可以让我遍历从一个大的JSON文件(大小为几百MB的)通过JSON对象。 我试图JsonTextReader从 Json.NET 象下面这样:

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 like below:

JsonTextReader reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
{
    if (reader.Value != null)
       Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
    else
       Console.WriteLine("Token: {0}", reader.TokenType);
}

但它返回令牌后令牌。 有没有更简单的方法,如果我需要整个对象,而不是令牌?

But it returns token after token. Is there any simpler way if I need whole object instead of tokens?

推荐答案

让我们假设你有一个类似的JSON数组:

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;
}

现在,该deserializetion部分

Now, the deserializetion part

JsonSerializer ser = new JsonSerializer();
ser.Converters.Add(new DummyConverter<TempClass>(t =>
    {
       //A callback method
        Console.WriteLine(t.text);
    }));

ser.Deserialize(new JsonTextReader(new StreamReader(File.OpenRead(fName))), 
                typeof(List<TempClass>));

和一个虚拟JsonConverter类拦截反序列化

And a dummy JsonConverter class to intercept the deserialization

public class DummyConverter<T> : JsonConverter
{
    Action<T> _action = null;
    public DummyConverter(Action<T> 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<T>(reader);
        _action( item);
        return null;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}