Deserting multiple json objects from a stream using Newtonsoft Json

I read the line NetworkStreamfor jsonand then deserialize using Newtonsoft.Json.

Sometimes two objects jsoncan be sent back and read at the same time in the stream. But Newtonsoft.Json serializergives me only one object.

For example, if I have the following line in a stream:

{"name":"John Doe","age":10}{"name":"Jane Doe","age":10}

If I deserialize a stream, it serializerreads the entire stream, but gives only the first object.

Is there a way to make serializerread only the first object from the stream and then read the next object in the next iteration of the loop?

the 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 am not getting an array json.

+4
2

, :

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-.

+3

,

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

Source: https://habr.com/ru/post/1693864/


All Articles