In this article you can find examples how to convert JSON into C# object using Json.NET (Newtonsoft.Json) library. It is available as a NuGet package for free, so you can easily install it from nuget.org repository.
Let’s create a JSON which will be used in below examples.
Next we need to assign it to string variable. We can do it either inline or save JSON to a file and then read the file content into variable.
Inline:
Read from file:
Now it’s time for the actual conversion of JSON to object. We’ve got two options here, depends on our needs. We can convert to dynamic object or to object of defined class.
1. Dynamic type
When we want to convert JSON to the object but don’t have any class which represents the JSON schema we can use dynamic type. To do so let’s use DeserializeObject method from JsonConvert class with specified result type as dynamic.
Next we can use received output as a regular object where property names are the same as in JSON document.
Print to screen:
Result:
2. Defined type – Person class
For demo purposes of parsing JSON into defined class we need to create it first. It’ll be Person class containing the same properties as our example JSON document.
Now having a Person type created we can use DeserializeObject function again but this time we’ll specify Person as an expected result.
Received value is object of Person class.
Let’s print the values to the console:
Result:
Need Help with Your C# Projects?
We offer expert support and development services for projects of any size. Contact us for a free consultation and see how we can help you succeed.
CONTACT US NOW