Home > Backend Development > C++ > How to Serialize and Deserialize Line-Delimited JSON in C#?

How to Serialize and Deserialize Line-Delimited JSON in C#?

Linda Hamilton
Release: 2025-01-22 16:36:12
Original
952 people have browsed it

How to Serialize and Deserialize Line-Delimited JSON in C#?

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);
}
Copy after login

This will generate a string with each Person object on a separate line:

{"personId": 1, "name": "John Smith", ...}
{"personId": 2, "name": "Jane Doe", ...}
Copy after login

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);
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template