JSON Serializers

Other Serialization technologies include Binary and XML Serialization.

System.Text.Json

New hotness <3

1
2
3
4
public string ToJson(object obj)
{
return JsonSerializer.Serialize(obj);
}

Json Serializer Options

1
2
3
4
5
6
7
8
9
10
public static JsonSerializerOptions IgnoreDefaultValues { get; } = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault, // ignore-all-default-value-properties
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // support camel case
Converters =
{
new JsonStringEnumConverter()
}
};

Json.NET / Newtonsoft Framework

Was integrated into ASP.NET even though it was 3rd party, I think its called Middleware. This lib is pretty much the de facto standard for JSON Serialization (Probably won awards, free beer & stuff!)

1
2
3
4
public string ToJson(object obj)
{
return JsonConvert.SerializeObject(obj);
}

System.Runtime.Serialization.Json

Class: DataContractJsonSerializer

An older, Microsoft-developed serializer that was integrated in previous ASP.NET versions until Newtonsoft.Json replaced it. Needs more code and sucks, don’t use it :D

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public string ToJson<T>(object obj)
{
var json = "[]";
var dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
using (var memoryStream = new MemoryStream())
{
dataContractJsonSerializer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
using (var streamReader = new StreamReader(memoryStream))
{
json = streamReader.ReadToEnd();
streamReader.Close();
}
memoryStream.Close();
}
return json;
}

--- CALL IT
var obj = new FizzbuzzEventBody() {
buzz_at = BuzzAt,
fizz_at = FizzAt,
lower_bound = LowerBound,
upper_bound = UpperBound
};
var json = ToJson<FizzbuzzEventBody>(obj);

System.Web.Script.Serialization

I remember using this ages ago in Web Forms and AjaxServer.asmx.cs files - I stopped using it after somebody showed me Json.NET

1
2
3
4
5
6
var list = new List<string>();
list.Add("some string value");

// slower built in 'JavaScriptSerializer'
var json = new JavaScriptSerializer().Serialize(list);
return json;

References