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

时间:2014-10-28 05:43:51

标签: c# json.net

我有一个JSON对象流,看起来有点像这样:

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

所以基本上是没有任何分隔符的JSON对象的连接列表。 使用JSON.NET将这些反序列化为IEnumerable<T>的正确方法是什么?目前我尝试过像

这样的东西
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电话后移动阅读器,但我该怎么做?

1 个答案:

答案 0 :(得分:13)

我认为如果你稍微改变你的循环,一切都应该有效:

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