Over a million developers have joined DZone.

Basic JSON data manipulation - not a Silverlight-only solution

·

If you read my previous article, I covered basic JSON data manipulation in the context of a Silverlight application. And although using the same tools to perform the same tasks in WPF or WinForms (or even Compact Framework) cannot be used, there is a third-party library called JSON.NET, that can help developers manipulate JSON data in a more organized manner.

First of all, you need to download the library from Codeplex. If you are interested in some detailed documentation, there is an official web site with online help content.

Create a new project (doesn’t matter what type) in Visual Studio. Now, depending on the targeted .NET version, you will be able to choose between the .NET 2.0, Compact Framework and the general .NET build of JSON.NET. For this article, I am using the general .NET build (for .NET 3.5 SP1). Add a reference to the library in your project.


 
Once done this, go to the window (or form, or maybe class) that you plan to use for JSON manipulation and add a reference to the Newtonsoft.Json namespace in the header:

using Newtonsoft.Json;

Now let’s start with the basics. I’d like to write a JSON file. To do this, I will use the JsonWriter class and JsontextWriter. JsonWriter is an abstract class, therefore I am instantiating JsonTextWriter, to which I am passing the existing TextWriter:

TextWriter textWriter = File.CreateText(@"D:\Temporary\myJson.json");
using (JsonWriter writer = new JsonTextWriter(textWriter))
{
writer.WriteStartObject();
writer.WritePropertyName("myProperty");
writer.WriteValue("myValue");
writer.WriteEndObject();
}

I am using TextWriter to write the actual JSON file and JsonWriter to write the data structure. In this specific case, I am building a very simple JSON structure that looks like this:

{ “myProperty” : “myValue” }

However, such simple structures are rarely used – the key elements in JSON can be nested and included in arrays. Nesting and array creation can be done with code similar to this:

TextWriter textWriter = File.CreateText(@"D:\Temporary\myJson.json");
using (JsonWriter writer = new JsonTextWriter(textWriter))
{
writer.WriteStartObject();
writer.WritePropertyName("root");
writer.WriteStartArray();
writer.WriteStartObject();
writer.WritePropertyName("element1");
writer.WriteValue("elValue1");
writer.WriteEndObject();
writer.WriteStartObject();
writer.WritePropertyName("element2");
writer.WriteValue("elValue2");
writer.WriteEndObject();
writer.WriteEndArray();
writer.WriteEndObject();
}

An array is not written directly as a value, but rather as a separate entity. Of course, you can write raw values instead to achieve the same result:

TextWriter textWriter = File.CreateText(@"D:\Temporary\myJson.json");
using (JsonWriter writer = new JsonTextWriter(textWriter))
{
writer.WriteStartObject();
writer.WritePropertyName("root");
writer.WriteRawValue(@"[{""element1"":""elValue1""},{""element2"":""elValue2""}]");
writer.WriteEndObject();
}

However, this might cause problems if the JSON you are passing is written the wrong way (therefore passing incorrect data structure). When compiling the application, no exception will be thrown and only the receiving JSON layer will encounter the existing invalid data formatting.

Notice that inside the array, after writer.WriteStartArray() I am creating a new object, that will contain both a property and a value. I cannot simply call writer.WritePropertyName(propertyname) because of the property scope –doing so will result in an exception being thrown.

Reading JSON data is done via JsonReader and JsonTextReader:TextReader treader = new StreamReader(@"D:\Temporary\myJson.json");

using (JsonReader reader = new JsonTextReader(treader))
{
while (reader.Read())
{
Debug.Print(reader.Value != null ? reader.Value.ToString() : string.Empty);
}
}

Here I am reading the newly written JSON file and I am reading through each entry inside of it. Note that here I am using the ternary operator to check whether the value is null (and it can be null). In case it is not null, it is being written in the Output console. In case the value is null, an empty string is inserted.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}