DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Data
  4. Basic JSON data manipulation - not a Silverlight-only solution

Basic JSON data manipulation - not a Silverlight-only solution

Denzel D. user avatar by
Denzel D.
·
Jun. 03, 10 · Interview
Like (0)
Save
Tweet
Share
8.47K Views

Join the DZone community and get the full member experience.

Join For Free

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.

JSON Data (computing)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Beyond Coding: The 5 Must-Have Skills to Have If You Want to Become a Senior Programmer
  • Key Elements of Site Reliability Engineering (SRE)
  • How Agile Architecture Spikes Are Used in Shift-Left BDD
  • 7 Ways for Better Collaboration Among Your Testers and Developers

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: