If using .Net 6.0 or later;
Default to using the built in System.Text.Json
parser implementation with Source Generation. Its a little more typing and compiling but, is more efficient at runtime.
The "easier to code" option below, still works but, less efficiently because it uses Reflection at runtime. The new method has some intentional, by design limitations. If you can't change your model to avoid those, the Reflection based method remains available.
e.g.
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
{
}
If using .Net Core 3.0 to .Net 5.0, it is time to upgrade;
Default to using the built in System.Text.Json
parser implementation.
e.g.
using System.Text.Json;
var json = JsonSerializer.Serialize(aList);
If stuck using .Net Core 2.2 or earlier;
Default to using Newtonsoft JSON.Net as your first choice JSON Parser.
e.g.
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(aList);
you may need to install the package first.
PM> Install-Package Newtonsoft.Json
For more details see and upvote the answer that is the source of this information.
For reference only, this was the original answer, many years ago;
// you need to reference System.Web.Extensions
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);
System.Web.Extensions
to useSystem.Web.Script.Serialization
: stackoverflow.com/a/18746092/1599699 stackoverflow.com/a/19299695/1599699