Importing Data Using Json.Net

A very frequent requirement that crops up a lot is the ability to import Json in some shape or form. For my work, importing Json is usually required during the content migration phase but there are far too many possibles.

Json and .Net

Importing Json is surprisingly easy when you use Json.Net. To get started open your Nuget repository and type in Json.Net:

json_net

All you have to do is create a simple object and decorate it with the Json.Net properties like so:

public class ImportClass
{
[JsonProperty(PropertyName = "name")]
public new virtual string Name { get; set; }
}

If we had this snippet of json:

{
"name": "jon"
}

Then by using this snippet Json.Net will auto-populate our objects for us:

var data = JsonConvert.DeserializeObject<ImportClass>(json);

Json Explained

I’m going to quickly cover the different types of Json you will likely need to import:

Arrays

In Json if you see anything with a square bracket then this means it’s an array:

numbers: [
1,
2,
3
]

You would then use this snippet to retrieve the array:

public class ImportClass
{
[JsonProperty(PropertyName = "numbers")]
public new virtual List<int> Name { get; set; }
}

Objects

When I first came across this within some Json I confused it with an array. In Json you can have child elements that can be an array or an element. The difference between them is the type of bracket used. ‘{ }’ is used for Object and ‘[]’ is used for Array in Json. They work slightly differently so if you try to import an object using the array code the DeserializeObject will throw a JsonSerializationException.

data: {
name: {
firstname: "jon",
surname: "jones"
}
}

In my experience, when you are importing data into Episerver,  you normally have a lot to process at the same time. I would recommend, in these circumstances, storing the Json as is in a field and then converting it into an object afterwards, like this:

public class ImportClass
{
public dynamic DataJson { get; set; }
public Dictionary<string, NameClass> DataObjects{ get; set; }
}
public class NameClass
{
[JsonProperty(PropertyName = "firstname")]
public new virtual string FirstName{ get; set; }
[JsonProperty(PropertyName = "surname")]
public new virtual string Surname{ get; set; }
}
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
var importedData = JsonConvert.DeserializeObject<ImportClass>(json, settings);
importedData .DataObjects= JsonConvert.DeserializeObject<Dictionary<string, NameClass>>(importedData.DataJson.ToString(), settings);
}

So far we’ve talked about importing multiple json files each containing a single item that we import. In some instance we might just have a Json file that contains an array for multiple items that needs importing, like so:

[
{
"name": "Alabama",
"abbreviation": "AL"
},
{
"name": "Alaska",
"abbreviation": "AK"
}
]

If you tried to import a single object when Json.Net is expecting an array you should see this 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.\r\nTo fix this error either change the JSON to...

In order to process these file we can still use the same type of import file, we just need to tell Json.Net that it’s a list and not a single item. This can be done my passing a List of items into Json.Net

List<JsonImportFile> jsonImportFile;
try
{
jsonImportFile = JsonConvert.DeserializeObject<List<JsonImportFile>>(jsonString);
}
catch (JsonSerializationException ex)
{
throw new InvalidOperationException();
}

Conclusion

Today’s guide has been a quick and dirty introduction about how to import Json into a .Net object using DeserializeObject. We’ve covered the different approach available to you for arrays and objects.

When you are trying to import a lot of Json and have sub-objects, a good approach is to import the child objects as Json in a single hit and then process the objects after the main import has taken place.

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

1 reply

Trackbacks & Pingbacks

  1. […] This object will be automatically populated via Json.Net and passed into a create page method. If you have never come across Json.Net before I’ve written an introduction about it in this guide: Importing Data Using Json.Net. […]

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *