How to deserialize JSON object to different types using Newtonsoft.Json?
I’ve recently publish few posts that explains how to work with Newtonsoft.Json framework. Make sure you check them out if you would like to learn more. In this post, I’ll tell you how to deserialize JSON object to different types using NewtonSoft.Json.
Deserialization is really simple using this framework when you are dealing with types that are known. There can be times when the type is not known and still the JSON response needs to be read and processed in some manner.
One of the example is getting a response from an API where the keys are dynamic or the structure is quite different that you don’t have a concrete type for it to process. But don’t worry as Newtonsoft.Json has got you covered for such cases.
I’m using a console application and my
Program.cs file looks like this:
static void Main(string args)
As you can see above, I’ve a class named
DifferentTypesDemo that has a static method named
ShowDemo, its implementation is shown below:
public class DifferentTypesDemo
public static void ShowDemo()
Console.WriteLine("---- using var ----");
Console.WriteLine("---- Dictionary ----");
Console.WriteLine("---- Anonymouns types ----");
Name = String.Empty,
IsHappy = false,
AnotherProperty = String.Empty
Let us understand at the code above.
- Line no. 5 defines a string object that has the JSON representation for data.
- Line no. 13 is the common way of using
JsonConvertand deserializing the data in string object to a .NET object. This can be used along with a specific type in cases where a type is known.
Newtonsoft.Jsonframework also supports deserializing the data into a Dictionary. In this case, it is of type
Dictionary<string, string>. Important thing to remember over here is that not everything can be deserialized into a dictionary.
This is really useful in cases when an API returns a response that is a collection and the key of the each item is dynamic – may be an int or string. So, this way of deserialization can be used to convert that data into a dictionary. And then loop over it to process it.
- One other way to deserialize using this framework is to use
JsonConvert. C# allows us to create anonymous types on the fly without creating a class. Line no. 19 defines such an anonymous object.
Next, on line no. 26, the author data is then deserialized using this special method. The resulting object will only have those members that were defined in anonymous type definition.
The last option is useful when you only want some part of the data to be converted to a .NET object. The non matched members within data will be ignored.
This framework is really great to deal with JSON data and .NET objects. I hope this post explains how to deserialize JSON object to different types using Newtonsoft.Json properly.