Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

c# - Deserialize multiple json objects from a stream using Newtonsoft Json

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...