一尘不染

使用JSON.NET解析JSON对象流的正确方法是什么?

c#

我有一些看起来像这样的JSON对象流:

{...}{...}{...}{...}...

因此,基本上是没有任何分隔符的JSON对象的串联列表。将它们反序列化为IEnumerable<T>使用JSON.NET
的正确方法是什么?此刻,我尝试了类似

var serializer = new JsonSerializer();
serializer.CheckAdditionalContent = false;

using (var reader = new StreamReader(stream))
using (var jsonReader = new JsonTextReader(reader)) {
    reader.SupportMultipleContent = true;
    reader.Read();
    while (reader.TokenType != JsonToken.None) {
        yield return serializer.Deserialize<TResult>(reader);
    }
}

但这失败了

Newtonsoft.Json.JsonSerializationException: Unexpected token while deserializing object: EndObject. Path '', line 1, position 55.
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
  at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
  at Newtonsoft.Json.JsonSerializer.Deserialize[T](JsonReader reader)

显然,Deserialize通话后我需要移动阅读器,但是我该怎么做?


阅读 272

收藏
2020-05-19

共1个答案

一尘不染

我认为,如果您稍微改变一下循环,一切都会正常进行:

public IEnumerable<TResult> ReadJson<TResult>(Stream stream)
{
    var serializer = new JsonSerializer();

    using (var reader = new StreamReader(stream))
    using (var jsonReader = new JsonTextReader(reader))
    {
        jsonReader.SupportMultipleContent = true;

        while (jsonReader.Read())
        {
            yield return serializer.Deserialize<TResult>(jsonReader);
        }
    }
}

请注意,IEnumerable<TResult>Stream传递给此方法的打开期间,您必须进行迭代:

using (var stream = /* some stream */)
{
    IEnumerable<MyClass> result = ReadJson<MyClass>(stream);

    foreach (var item in result)
    {
        Console.WriteLine(item.MyProperty);
    }
}

示例: https
//dotnetfiddle.net/Y2FLuK

JsonNet站点上的示例:使用JsonReader读取多个片段

2020-05-19