Deserializing JSON to Object Without Creating Custom Class






4.06/5 (13 votes)
Deserializing JSON to object without creating any custom class using C# Dynamic type
Introduction
Usually, we create custom classes to store the deserialized data from json. These custom classes were no more required if we use dynamic type which is introduced in C# 4.0.
Using the Code
Usual way of deserializing json using Newtonsoft:
class Car
{
public string Name;
public string Company;
public int Id;
}
class Program
{
static void Main(string[] args)
{
Car car = new Car() { Id = 1, Name = "Polo", Company = "VW" };
string serialized = JsonConvert.SerializeObject(car);
Car deserialized= JsonConvert.DeserializeObject<Car>(serialized);
Console.WriteLine(deserialized.Company + " " + deserialized.Name);
Console.ReadLine();
}
}
New way using dynamic:
class Program
{
static void Main(string[] args)
{
Car car = new Car() { Id = 1, Name = "Polo", Company = "VW" };
string serialized = JsonConvert.SerializeObject(car);
dynamic deserialized = JsonConvert.DeserializeObject(serialized);
Console.WriteLine(deserialized.Company + " " + deserialized.Name);
Console.ReadLine();
}
}
As dynamic type skips the compile time binding and performs the binding dynamically, intellisense support will not be available,
Also, if you try to access a non-existant property like deserialized.Price
which is not in the json, it will throw neither compile time or run time error. It will be considered as null
and no code break.