How to deserialize and serialize JSON(read json from file, write json to file) using C# and Visual Studio .NET Framework 3.5

Error message and syntax references: serializer.Deserialize, Invalid JSON primitive, C#, System.Web.Script.Serialization, Int32 depth.

This blog post shows you how to work with JSON in a Microsoft development environment like MicrosoftSQL Server Integration Services (SSIS) which, in my case, uses a combination of the .NET Framework 3.5 and the programming language C#.

In C# the best way to read and write JSON is to create C# class[es] which map to the JSON data.

Classes

SingleThing describes … a single thing.

public class SingleThing
{
public string thingName{ get; set; }
public string thingDescription{ get; set; }
}

Things stores … many single things

public class Things
{
public List<SingleThing> manySingleThings { get; set; }

Important

Now remember that we are mapping the keys in JSON to variable names in C# classes. For example if the outer wrapper (List of Objects) in JSON is manySingleThings then the variable name (List of single things) in C# must be called manySingleThings.

Creating the JSON

This code below creates the wrapper/outer container of the JSON {“manySingleThings“:[]}

Dictionary<string, object> manySingleThings = new Dictionary<string, object>();

This code below creates the internal containers in the JSON file {“manySingleThings“:[ {}, {}]}

List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();

… and this creates data in the JSON file {“manySingleThings“:[ {“a”: “one”}, {“b”: “two”}]}

Dictionary<string, object> row;

Putting the JSON together

512px-russian_dolls

By Lachlan Fearnley (Own work) [CC BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0)%5D, via Wikimedia Commons

Once the above variables have been declared/initialized let’s start creating the JSON. Think of this process as working from the inside out. For example, we are getting the smallest Matryoshka doll and putting it inside the larger/outer wrappers.

row.Add("a", "one");
rows.Add(row);
manySingleThings.Add("manySingleThings", rows);

{“manySingleThings“:[ {“a”: “one”}, {“b”: “two”}]}

Serializing the JSON

Add the reference (import the library)

using System.Web.Script.Serialization;

Perform the serialization

System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

Write the serialized JSON to a file – note this is the only time we reference the Class name of Things. Other than this we are always mapping against JSON keys and C# Class VARIABLE names (not CLASS names).

System.IO.File.WriteAllText(outputFileName, serializer.Serialize(Things));

Output can be checked using JSON Lint

{"manySingleThings":[ {"a": "one"}, {"b": "two"}]}

 Deserializing JSON (reading JSON from file and creating C# classes)

As we mentioned above you need to have the C# variables which reflect the JSON data (see the Things and SingleThing classes above.

Read the JSON file from disk and deserialize (note the deserialize section refers to our Things class). This is neat as the deserializer simply reads all of the JSON from the string jrf and packs it all away in the Things class – the C# class which we defined above that contains a C# List of SingleThing classes.

string jrf = System.IO.File.ReadAllText(this.jsonFileLocation);
JavaScriptSerializer serializer = new JavaScriptSerializer();
private List jsonAsList = new List();
jsonAsList = serializer.Deserialize<List>(jrf.ToString());

How to access data stored in the Things Class

So now that we are able to create, write and read JSON we need to have a mechanism to use the data eg. find values buried in the (manySingleThings) List of (SingleThing) C# classes. This is surprisingly easy.

We just ask the “jsonAsList” to retrieve the entire C# class which contains a particular variable value that we are interested in.

SingleThing theNeedle = jsonAsList.Find(x => x.thingName.ToString() == "Trevor");

Now that we have the new class instantiated we can access its variables

string thingName = theNeedle.thingName;
//Trevor
string descriptionOfAThing = theNeedle.thingDescription;
//Likes cups of tea
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s