Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Deserializing JSON to Object Without Creating Custom Class

0.00/5 (No votes)
9 Jun 2016 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here