使用Newtonsoft Json从流中反序列化多个json对象 [英] Deserialize multiple json objects from a stream using Newtonsoft Json
问题描述
我正在读取json
字符串的NetworkStream
,然后使用Newtonsoft.Json
反序列化.
I am reading a NetworkStream
for json
string and then deserializing it using Newtonsoft.Json
.
有时,两个json
对象可以背对背发送并在流上同时读取.但是Newtonsoft.Json
serializer
只给我一个物体.
Sometimes, two json
objects could be sent back to back and read at the same time on the stream. But the Newtonsoft.Json
serializer
gives me only one object.
例如,如果我在流上有以下字符串:
For example, if I have the following string on the stream:
{"name":"John Doe","age":10}{"name":"Jane Doe","age":10}
如果我反序列化该流,则serializer
读取整个流,但仅给出第一个对象.
If I deserialize the stream, the serializer
reads the entire stream, but gives only the first object.
是否有一种方法可以使serializer
仅读取流中的第一个对象,然后在下一次循环迭代中读取下一个对象?
Is there a way to make the serializer
read only the first object from the stream and then read the next object in the next iteration of a loop?
代码:
public static Person Deserialize(Stream stream)
{
var Serializer = new JsonSerializer();
var streamReader = new StreamReader(stream, new UTF8Encoding());
return Serializer.Deserialize<Person>(new JsonTextReader(streamReader));
}
我无法反序列化为列表,因为没有收到json
数组.
I cannot desrialize as a list because I'm not receiving a json
array.
推荐答案
我认为您可以这样做:
public static IList<Person> Deserialize(Stream stream) {
var serializer = new JsonSerializer();
var streamReader = new StreamReader(stream, new UTF8Encoding());
var result = new List<Person>();
using (var reader = new JsonTextReader(streamReader)) {
reader.CloseInput = false;
// important part
reader.SupportMultipleContent = true;
while (reader.Read()) {
result.Add(serializer.Deserialize<Person>(reader));
}
}
return result;
}
重要的部分是SupportMultipleContent
属性,它通知读者并排存在多个json对象.
Important part is SupportMultipleContent
property, which notifies reader that there might be multiple json objects side to side.
这篇关于使用Newtonsoft Json从流中反序列化多个json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!