Json.NET - Converting Collections

Json.NET supports serialization and deserialization of array, generic list, dictionaries and custom collections too.

Serialization

To serialize collection, you needs to call the SerializeObject method and pass the collection object to it as the parameter and Json.NET converts it to json string automatically without needing any other configuration.

In the example given below, we have created a class User with two properties, Name and Age. And in the main method we are intializing a list of users and to serialize the list, we are passing it to the SerializeObject method in JsonConvert class.

string jsonText = JsonConvert.SerializeObject(usrs, Formatting.Indented);

Deserialization

Deserialization is pretty straightforward. We can use the DeserializeObject method in the JsonConvert class to do that as shown in the example below.

The statement

var users  = JsonConvert.DeserializeObject<List<User>>(jsonText);

is doing the conversion and here we have the json text that needs to be converted as paramter to the method and also mentioned the type it needs to transformed into

Similarly for deserializing dictionaries, we can use the following statement

Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonInput);


No Comments

Add a Comment