Click or drag to resize
Json.NETSerializing Collections
 

Json.NET has excellent support for serializing and deserializing collections of objects.

Serializing Collections

To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for. Json.NET will serialize the collection and all of the values it contains.

Serializing Collections
 1Product p1 = new Product
 2{
 3    Name = "Product 1",
 4    Price = 99.95m,
 5    ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
 6};
 7Product p2 = new Product
 8{
 9    Name = "Product 2",
10    Price = 12.50m,
11    ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
12};
13
14List<Product> products = new List<Product>();
15products.Add(p1);
16products.Add(p2);
17
18string json = JsonConvert.SerializeObject(products, Formatting.Indented);
19//[
20//  {
21//    "Name": "Product 1",
22//    "ExpiryDate": "2000-12-29T00:00Z",
23//    "Price": 99.95,
24//    "Sizes": null
25//  },
26//  {
27//    "Name": "Product 2",
28//    "ExpiryDate": "2009-07-31T00:00Z",
29//    "Price": 12.50,
30//    "Sizes": null
31//  }
32//]
Deserializing Collections

To deserialize JSON into a .NET collection just specify the collection type you want to deserialize to. Json.NET supports a wide range of collection types.

Deserializing Collections
 1string json = @"[
 2  {
 3    'Name': 'Product 1',
 4    'ExpiryDate': '2000-12-29T00:00Z',
 5    'Price': 99.95,
 6    'Sizes': null
 7  },
 8  {
 9    'Name': 'Product 2',
10    'ExpiryDate': '2009-07-31T00:00Z',
11    'Price': 12.50,
12    'Sizes': null
13  }
14]";
15
16List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
17
18Console.WriteLine(products.Count);
19// 2
20
21Product p1 = products[0];
22
23Console.WriteLine(p1.Name);
24// Product 1
Deserializing Dictionaries

Using Json.NET you can also deserialize a JSON object into a .NET generic dictionary. The JSON object's property names and values will be added to the dictionary.

Deserializing Dictionaries
1string json = @"{""key1"":""value1"",""key2"":""value2""}";
2
3Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
4
5Console.WriteLine(values.Count);
6// 2
7
8Console.WriteLine(values["key1"]);
9// value1
See Also