Serialization (JSON)

You can serialize to JSON using the .net core framework:

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
27
28
using System.Runtime.Serialization.Json;

public string Serialize<T>(object obj)
{
var json = "[]";
var js = new DataContractJsonSerializer(typeof(T));
using (var ms = new MemoryStream())
{
js.WriteObject(ms, obj);
ms.Position = 0;
using (var sr = new StreamReader(ms))
{
json = sr.ReadToEnd();
sr.Close();
}
ms.Close();
}
return json;
}

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

References

Newtonsoft Framework

1
2
3
4
5
6
7
8
9
10
11
12
13
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Sizes": [
// "Small"
// ]
// }
1
2
3
4
5
6
7
8
9
10
11
12
13
string json = @"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys