Deserialize multiple json objects from a stream using Newtonsoft Json

雨燕双飞 提交于 2019-12-08 20:21:09

问题


I am reading a NetworkStream for json string and then deserializing it using Newtonsoft.Json.

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}

If I deserialize the stream, the serializer reads the entire stream, but gives only the first object.

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?

Code:

public static Person Deserialize(Stream stream)
{
    var Serializer = new JsonSerializer();
    var streamReader = new StreamReader(stream, new UTF8Encoding());
    return Serializer.Deserialize<Person>(new JsonTextReader(streamReader));
}

I cannot desrialize as a list because I'm not receiving a json array.


回答1:


I think you can do it like this:

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;
}

Important part is SupportMultipleContent property, which notifies reader that there might be multiple json objects side to side.




回答2:


you can try it doing like this

        var httpRequest = HttpContext.Current.Request;
        // This list will have all the stream objects
        var persons = new List<Person>();
        if (httpRequest.Files.Count > 0)
        {
            for (var obj = 0; doc < httpRequest.Files.Count; obj++)
            {
                var postedFile = httpRequest.Files[obj];
                var bytes = new byte[postedFile.ContentLength];
                postedFile.InputStream.Read(bytes, 0, postedFile.ContentLength);
                persons.Add(Serializer.Deserialize<Person>(new JsonTextReader(new StreamReader(new MemoryStream(bytes)))));
            }
        }


来源:https://stackoverflow.com/questions/48882653/deserialize-multiple-json-objects-from-a-stream-using-newtonsoft-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!