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
Connecting Azure Blob Storage account using Managed Identity
Posted 12/9/2022Securing Azure KeyVault connections using Managed Identity
Posted 11/26/2022Manage application settings with Azure KeyVault
Posted 11/9/2022Adding Serilog to Azure Functions created using .NET 5
Posted 4/3/2021Learn how to split log data into different tables using Serilog in ASP.NET Core
Posted 4/23/2020