Home > Backend Development > C++ > Can JavascriptSerializer Serialize Lists to JSON in .NET?

Can JavascriptSerializer Serialize Lists to JSON in .NET?

Mary-Kate Olsen
Release: 2025-01-11 06:53:42
Original
303 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

Consider installing this package if necessary: ​​

<code>PM> Install-Package Newtonsoft.Json</code>
Copy after login

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>
Copy after login

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!

source:php.cn
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