65.9K
CodeProject is changing. Read more.
Home

Deserializing JSON to Object Without Creating Custom Class

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.06/5 (13 votes)

Jun 10, 2016

CPOL
viewsIcon

52824

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.