Home >Backend Development >C++ >How to Parse a Stream of JSON Objects Using JSON.NET?
Parse JSON object stream using JSON.NET
JSON.NET provides a convenient solution to deserialize a connected stream of JSON objects. In achieving this, you may run into the issue of how to advance the reader after each deserialization.
The code snippet you provided attempts to deserialize a stream of JSON objects, but fails due to an unexpected token error. To resolve this issue, modify the code as follows:
<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() && !jsonReader.EOF) // 添加EOF检查 { try { yield return serializer.Deserialize<TResult>(jsonReader); } catch (JsonReaderException ex) { // 处理JSON读取异常,例如跳过无效的JSON对象 Console.WriteLine($"JSON解析错误: {ex.Message}"); // 可选:在此处添加日志记录或其他错误处理机制 } } } }</code>
In this modified code, the loop has been adjusted to read each JSON object from the stream and then produce the deserialized result. It is important to iterate over the returned IEnumerable<TResult>
while the provided stream is open to prevent object disposal errors. Additionally, a !jsonReader.EOF
check was added to avoid infinite loops, and a try-catch
block was added to handle potential JsonReaderException
such as encountering an invalid JSON object.
Here is an example:
<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>
For more information on using JsonReader to handle multiple JSON fragments, please refer to the official JSON.NET documentation.
The above is the detailed content of How to Parse a Stream of JSON Objects Using JSON.NET?. For more information, please follow other related articles on the PHP Chinese website!