Home >Backend Development >C++ >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
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
<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!