Home >Backend Development >C++ >How Can I Serialize a List to JSON Using System.Text.Json?

How Can I Serialize a List to JSON Using System.Text.Json?

Susan Sarandon
Susan SarandonOriginal
2025-01-11 06:02:44546browse

How Can I Serialize a List to JSON Using System.Text.Json?

Serialize list to JSON using System.Text.Json

In your scenario, the ObjectInJson attribute contains a serialized object containing nested lists. Currently, you are manually generating a JSON string of a list of these objects. This approach is error-prone and not as efficient as using a dedicated JSON serializer.

.NET provides the System.Text.Json library for efficient and reliable JSON serialization. Use it in your scenario:

<code class="language-csharp">using System.Text.Json;

var aList = new List<MyObjectInJson>
{
    new(1, "1"),
    new(2, "2")
};

var json = JsonSerializer.Serialize(aList);
Console.WriteLine(json);</code>

This code will generate a JSON string representing a list of MyObjectInJson objects. The JSON string will contain nested lists as string arrays.

The above is the detailed content of How Can I Serialize a List to JSON Using System.Text.Json?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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