Home >Backend Development >C++ >Can JavascriptSerializer Serialize Lists to JSON in .NET?
Can JavascriptSerializer in .NET serialize a list to JSON?
Suppose your object model contains MyObjectInJson
, whose property ObjectInJson
stores the serialized version of the nested list. Currently, you are manually serializing the list like this:
<code class="language-csharp">StringBuilder TheListBuilder = new StringBuilder(); TheListBuilder.Append("["); int TheCounter = 0; foreach (MyObjectInJson TheObject in TheList) { TheCounter++; TheListBuilder.Append(TheObject.ObjectInJson); if (TheCounter != TheList.Count()) { TheListBuilder.Append(","); } } TheListBuilder.Append("]"); return TheListBuilder.ToString();</code>
JavascriptSerializer
Is it possible to achieve the same result?
Alternatives to JavascriptSerializer
For .NET 6.0 and above, it is recommended to use the built-in System.Text.Json
parser. It serializes lists efficiently without reflection, like this:
<code class="language-csharp">using System.Text.Json; using System.Text.Json.Serialization; var aList = new List<myobjectinjson> { new(1, "1"), new(2, "2") }; var json = JsonSerializer.Serialize(aList, Context.Default.ListMyObjectInJson); Console.WriteLine(json); return; public record MyObjectInJson ( long ObjectId, string ObjectInJson ); [JsonSerializable(typeof(List<myobjectinjson>))] internal partial class Context : JsonSerializerContext { }</code>
For previous .NET versions (e.g., Core 2.2 and earlier), Newtonsoft JSON.Net is a viable alternative:
<code class="language-csharp">using Newtonsoft.Json; var json = JsonConvert.SerializeObject(aList);</code>
Consider installing this package if necessary:
<code>PM> Install-Package Newtonsoft.Json</code>
For ease of reference, the original method using JavaScriptSerializer
is provided:
<code class="language-csharp">// 需要引用 System.Web.Extensions using System.Web.Script.Serialization; var jsonSerialiser = new JavaScriptSerializer(); var json = jsonSerialiser.Serialize(aList);</code>
The above is the detailed content of Can JavascriptSerializer Serialize Lists to JSON in .NET?. For more information, please follow other related articles on the PHP Chinese website!