×
Namespaces

Variants
Actions

How to handle JSON strings with Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search
Featured Article
23 Mar
2014

This article explains how to handle (serialize and deserialize) JSON strings using the Json.NET library.

WP Metro Icon File.png
WP Metro Icon Web.png
WP Metro Icon WP8.png
Article Metadata
Code ExampleTested with
SDK: Windows Phone 8.0 SDK
Devices(s): Nokia Lumia 820
Compatibility
Platform(s):
Windows Phone 8
Article
Created: mfabiop (10 Mar 2014)
Last edited: influencer (25 Mar 2014)

Contents

Introduction

Most of the mobile applications need to communicate with external services (existing services like Twitter or Facebook, or with a new service that the developer must implement too). One of the most common ways to code structured data is using JSON format. JSON (JavaScript Object Notation) is a lightweight data-interchange format, very easy to read and parse by humans or computers. JSON are built on two data structures, as shown below:

JSON Objects

A collection of key-value entries, where each value can be a primitive type or another JSON structure

{
Name : "Marcos",
Address : {
Street : "Marcos' street",
Country : "Brazil",
City : "Campina Grande"
}
}

JSON Arrays

A list of JSON structures (JSON arrays or JSON objects).

[
{
Name : "Marcos",
Country : "Brazil"
},
{
Name : "John",
Country : "England"
}
]

There are a lot of libraries to handle JSON strings. These libraries are able to convert JSON strings to variables and vice-versa. This make possible, and easy, to communicate with external services that use this format to exchange data. This article will focus on Json.NET library and show how to serialize (converting C# objects to JSON strings), deserialize (converting JSON strings to C# objects) and perform searches inside JSON structures.

Installing Json.NET Library

The Json.NET library is provided as a Nuget package, so it is very easy to install it: Right click on your project and select "Manage NuGet Packages..."; Type "json.net" in the search field and click "Install".

Installing JsonNET 1.png

Deserialize

As said before, deserialize (or parse) is used to get a JSON structure (represented as string) and convert it to variables that can be used in your project.

Parsing a JSON array

using Newtonsoft.Json.Linq;
 
public void ParseArray() {
string jsonArrayAsString = "[ { Name : \"Marcos\", Country : \"Brazil\" }, { Name : \"John\", Country : \"England\" }]";
JArray jsonArray = JArray.Parse(jsonArrayAsString);
JToken jsonArray_Item = jsonArray.First;
while (jsonArray_Item != null)
{
string name = jsonArray_Item.Value<string>("Name");
string country = jsonArray_Item.Value<string>("Country");
//Be careful, you take the next from the current item, not from the JArray object.
jsonArray_Item = jsonArray_Item.Next;
}
}

Parsing a JSON object

using Newtonsoft.Json.Linq;
 
public void ParseObject()
{
string jsonObjectAsString = "{ Name : \"Marcos\", Country : \"Brazil\" }";
JObject jsonObject = JObject.Parse(jsonObjectAsString);
string name = jsonObject.Value<string>("Name");
string country = jsonObject.Value<string>("Country");
}

Serialize

Serialize is used to get some C# variables and convert them to a JSON string.

Serialize a array

public string StringifyArray(string[] names, string[] countries)
{
JArray jsonArray = new JArray();
for (int i = 0; i < names.Length; i++)
{
JObject jsonObject = new JObject();
jsonObject["Name"] = names[i];
jsonObject["Country"] = countries[i];
jsonArray.Add(jsonObject);
}
return jsonArray.ToString();
}

Serialize a object

public string StringifyObject(string name, string country)
{
JObject jsonObject = new JObject();
jsonObject["Name"] = name;
jsonObject["Country"] = country;
return jsonObject.ToString();
}

Search

At this point you can think that the Json.NET library is good for serialization and deserialization of JSON objects, but it is not good enough to search inside JSON objects. This is not true! To do searches in JSON structures there are two great methods (SelectToken and SelectTokens). Take a look at the example below:

public void Search()
{
string jsonObjectAsString = "{ Name : \"Marcos\", Country : \"Brazil\", Friends : [ {Name : \"John\", Country : \"England\"} , {Name : \"Chan\", Country : \"China\"} ] }";
JObject jsonObject = JObject.Parse(jsonObjectAsString);
List<JToken> friendCountries = jsonObject.SelectTokens("Friends[*].Country").ToList();
for (int i = 0; i < friendCountries.Count; i++)
{
System.Diagnostics.Debug.WriteLine(friendCountries[i].ToString());
}
}

Take a look at the SelectTokens parameter. Basically what it is doing is getting the 'Country' field of each friend of 'Marcos'. The SelectTokens parameter is a JPath expression. JPath expressions are a powerful tool to perform searches in JSON structures.

These are some examples of JPath expressions:

  • Friends[?(@.Name=='John')].Country Get the country name of all friends with name 'John'.
  • Friends[0].Country Get the country name of the first friend.
  • Friends[:2] Get the first two friends in the list.

The difference between SelectToken and SelectTokens is that the first one returns only one result. SelectToken will throw an exception if your JPath expression returns more than one result.

To see more details about JPath expressions, click here.

This page was last modified on 25 March 2014, at 18:56.
1103 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×