Serialization and deserialization of line-delimited JSON in C#
When using JSON.NET and C# 5, it may be necessary to serialize and deserialize objects to line-delimited JSON according to Google BigQuery's specifications. This format uses newlines to separate each object.
Serialization
To serialize a list of objects into line-delimited JSON, you can use JsonTextWriter
:
using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Converters; var people = new List<Person> { }; // 注意此处Person首字母大写 using (var writer = new StringWriter()) { var settings = new JsonSerializerSettings() { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore }; var jsonSerializer = new JsonSerializer(settings); jsonSerializer.Serialize(writer, people); }
This will generate a string with each Person object on a separate line:
{"personId": 1, "name": "John Smith", ...} {"personId": 2, "name": "Jane Doe", ...}
Deserialization
To deserialize line-delimited JSON into a list of objects, you can use a combination of JsonTextReader
and JsonSerializer
:
using System.IO; using Newtonsoft.Json; using (var reader = new StringReader(json)) using (var jsonReader = new JsonTextReader(reader)) { jsonReader.SupportMultipleContent = true; var jsonSerializer = new JsonSerializer(); while (jsonReader.Read()) { var person = jsonSerializer.Deserialize<Person>(jsonReader); // 注意此处Person首字母大写 people.Add(person); } }
This will populate the people list with the deserialized Person object.
Improvement notes: Corrected person
to Person
in the code example to comply with the C# naming convention. The rest of the text keeps the original meaning unchanged, with only minor adjustments to the sentences to make the expression more fluent and natural.
The above is the detailed content of How to Serialize and Deserialize Line-Delimited JSON in C#?. For more information, please follow other related articles on the PHP Chinese website!