使用JSON.NETparsingJSON对象stream的正确方法是什么?
我有一个JSON对象stream,看起来有点像这样:
{...}{...}{...}{...}...
所以基本上是没有任何分隔符的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
调用后,显然我需要移动读者,但是我该怎么做呢?
我想如果你稍微改变你的循环,一切都应该工作:
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); } } }
请注意,当传递给此方法的Stream
打开时,您必须迭代IEnumerable<TResult>
:
using (var stream = /* some stream */) { IEnumerable<MyClass> result = ReadJson<MyClass>(stream); foreach (var item in result) { Console.WriteLine(item.MyProperty); } }
例如: https : //dotnetfiddle.net/Y2FLuK