Home >Backend Development >C++ >How to Deserialize a Stream of Concatenated JSON Objects in JSON.NET?

How to Deserialize a Stream of Concatenated JSON Objects in JSON.NET?

Susan Sarandon
Susan SarandonOriginal
2025-01-09 21:28:47442browse

How to Deserialize a Stream of Concatenated JSON Objects in JSON.NET?

Parse JSON object stream using JSON.NET

When deserializing a concatenated stream of JSON objects without delimiters, the problem is how to handle it correctly using JSON.NET.

The attempted solution involves using a stream reader, a JSON text reader and a custom loop to deserialize the stream into an IEnumerable. However, this method encountered an exception indicating an unexpected 'EndObject' tag.

To correct this, some modifications need to be made to the loop:

<code class="language-csharp">public IEnumerable<TResult> ReadJson<TResult>(Stream stream)
{
    var serializer = new JsonSerializer();

    using (var reader = new StreamReader(stream))
    using (var jsonReader = new JsonTextReader(reader))
    {
        jsonReader.SupportMultipleContent = true;

        while (jsonReader.Read())
        {
            yield return serializer.Deserialize<TResult>(jsonReader);
        }
    }
}</code>

It is important to note that the returned IEnumerable must be iterated over while the stream remains open:

<code class="language-csharp">using (var stream = /* some stream */)
{
    IEnumerable<MyClass> result = ReadJson<MyClass>(stream);

    foreach (var item in result)
    {
        Console.WriteLine(item.MyProperty);
    }
}</code>

This technology is on the dotnetfiddle website (https://www.php.cn/link/a3b1c195e3033e5086eb7482c0942e4a.

The above is the detailed content of How to Deserialize a Stream of Concatenated JSON Objects in JSON.NET?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn