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

How to Parse a Stream of Concatenated JSON Objects with JSON.NET?

Linda Hamilton
Release: 2025-01-09 21:16:41
Original
166 people have browsed it

How to Parse a Stream of Concatenated JSON Objects with JSON.NET?

Use JSON.NET to parse JSON object stream

Use JSON.NET to deserialize a delimiter-free continuous stream of JSON objects into IEnumerable<T> as follows:

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

    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>
Copy after login

Usage:

The following example demonstrates iterating IEnumerable<T> while a stream is 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>
Copy after login

Other notes:

  • Make sure to iterate IEnumerable<T> while the stream is open.
  • Set CheckAdditionalContent to false to prevent exceptions when extra content is encountered after deserialization.

Example:

Please refer to the following example on the JSON.NET website: "Read multiple fragments using JsonReader" (//m.sbmmt.com/link/b0a3f2a0d6f86051e6ab6c49d6d99e75).

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template