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!