我有一个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
电话后移动阅读器,但我该怎么做?
答案 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);
}
}