Home >Backend Development >C++ >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>
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>
Other notes:
IEnumerable<T>
while the stream is open. 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" (https://www.php.cn/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!