Serialization and Deserialization of Line Delimited JSON (LDJSON) in C#
Understanding this process is critical when you need to serialize and deserialize objects into row-delimited JSON (LDJSON) format (commonly used in Google BigQuery data preparation). LDJSON represents data as a series of newline-delimited JSON objects.
Manually parse LDJSON data
JsonTextReader in Json.NET provides a way to manually parse LDJSON data. JsonTextReader can handle contiguous JSON objects by setting the SupportMultipleContent flag to true.
First JSON example (simple object)
Consider the following LDJSON data:
<code>{"some":"thing1"} {"some":"thing2"} {"some":"thing3"}</code>
The analysis method is as follows:
<code class="language-csharp">var json = "{\"some\":\"thing1\"}\r\n{\"some\":\"thing2\"}\r\n{\"some\":\"thing3\"}"; var jsonReader = new JsonTextReader(new StringReader(json)) { SupportMultipleContent = true // 允许多个JSON对象 }; var jsonSerializer = new JsonSerializer(); while (jsonReader.Read()) { var foo = jsonSerializer.Deserialize<foo>(jsonReader); }</code>
Second JSON example (nested object)
For more complex JSON:
<code class="language-json">{"kind": "person", "fullName": "John Doe", "age": 22, "gender": "Male", "citiesLived": [{ "place": "Seattle", "numberOfYears": 5}, {"place": "Stockholm", "numberOfYears": 6}]} {"kind": "person", "fullName": "Jane Austen", "age": 24, "gender": "Female", "citiesLived": [{"place": "Los Angeles", "numberOfYears": 2}, {"place": "Tokyo", "numberOfYears": 2}]}</code>
Using the same approach, add each deserialized object to the list:
<code class="language-csharp">var json = "{...}"; // 定义JSON字符串 var jsonReader = new JsonTextReader(new StringReader(json)) { SupportMultipleContent = true }; var jsonSerializer = new JsonSerializer(); var listOfPeople = new List<person>(); while (jsonReader.Read()) { listOfPeople.Add(jsonSerializer.Deserialize<person>(jsonReader)); }</code>
Note: Json.Net 10.0.4 and above also supports comma-separated JSON entries, providing additional flexibility.
The above is the detailed content of How to Serialize and Deserialize Line Delimited JSON (LDJSON) in C#?. For more information, please follow other related articles on the PHP Chinese website!