使用Newtonsoft Json从流中反序列化多个json对象 [英] Deserialize multiple json objects from a stream using Newtonsoft Json

查看:567
本文介绍了使用Newtonsoft Json从流中反序列化多个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆