In this tutorial, you will learn how to serialise and deserialise data from an API using Json.Net. When building a C# application, importing JSON is surprisingly easy when you use JSON.NET.
To get started within JSON.NET, within Visual Studio, open your NuGet repository and type in Json.Net
. The package looks like this:
To get started, create a simple class with properties that mirrors the data you want to import from the API. For each property, decorate it with the JsonProperty
attribute. Then name needs to map the Name in JSON. Using this approach means you can use normal C# naming conventions, rather than having to use Javascript-based names:
Using this code would allow you to convert this snippet of JSON:
Json.Net will then auto-populate the object for us:
JSON Explained
I'm going to quickly cover the different data types that you may need to import:
Arrays: When using JSON if you see anything enclosed with a square bracket []
it's an array:
You would ten map the array to a C# list, to import the array:
Objects: Objects define a unique combination of properties. Objects are defined using the curly braces '{ }' notation.
Based on my experience, when you are importing a lot of data, I recommend storing objects in a string field first and then converting the data into an object as a seperate step, like this:
In some instances, you might just have a JSON response that contains an array:
It is common to get arrays and objects mixed up. If you try to import an array as an object, you will encounter an error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type '' because the type requires a JSON object (e.g. {"name"\"value"}) to deserialize correctly. To fix this error either change the JSON to...
If you encouter an error like this, you need to change the underlining backing type to a List<T>
:
Today's guide has been a quick and dirty introduction on how to import Json into a C# using Json.Net. Converting data is simple enough. Remeber, do not get arrays and objects mixed up. Happy Coding 🤘