Many people use JSON rather than XML in the web for many reasons :
- JSON requires less tags than XML – XML items must be wrapped in open and close tags whereas JSON you just name the tag once.
- JSON is better at helping procedural decisions in your JavaScript based on objects and their values (or methods).
- JSON is easier to read than XML (at less for many developers).
- JSON is an ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
- Between many more ...
Therefore, if a webservice decides (i really doubt it) to offer a service only in JSON format, you'll be stucked for a while if you don't know how to properly handle JSON data with C#.
Learn in this article how to manipulate JSON using JSON.NET library in all its ways (read,serialize, deserialize etc) in windows forms.
Requirements
- Visual Studio with NuGet Package Manager (>=2010).
Installing JSON.NET
Proceed to create a Winforms application as you usual do it targetting the latest version of .NET Framework. Now after the creation, we are going to add JSON.NET library as a dependency in our project.
JSON.NET is a high-performance JSON framework for .NET platform, it allow you to serialize and deserialize any .NET object with Json.NET's powerful JSON serializer.
Why use JSON.NET library ?
- Json.NET makes the simple easy and the complex possible.
- Create, parse, query and modify JSON using Json.NET's JObject, JArray and JValue objects.
- Json.NET supports Windows, Windows Store, Windows Phone, Mono, and Xamarin.
- Json.NET is open source software and is completely free for commercial use.
- 50% faster than DataContractJsonSerializer, and 250% faster than JavaScriptSerializer.
As the library is of high performance, see the following chart that compares JSON.NET performance between other known libraries :
To install, right click on your project in the solution explorer and select Manage NuGet Packages
.
When the search menu appears, type JSON.NET
, select the WinForms distributtion and install it.
As with every version of Visual Studio, the interface may vary, just be sure to install a distribution of Newtonsoft.Json by The James Newton-King located in the nuget.org Package source, in this example we're using Visual Studio 2015.
Follow the installation setup (accept terms and install). During the installation you should see related information about the process in the console :
Attempting to gather dependency information for package 'Newtonsoft.Json.8.0.3' with respect to project 'UniversalSandbox', targeting '.NETFramework,Version=v4.5.2'
Attempting to resolve dependencies for package 'Newtonsoft.Json.8.0.3' with DependencyBehavior 'Lowest'
Resolving actions to install package 'Newtonsoft.Json.8.0.3'
Resolved actions to install package 'Newtonsoft.Json.8.0.3'
GET https://api.nuget.org/packages/newtonsoft.json.8.0.3.nupkg
OK https://api.nuget.org/packages/newtonsoft.json.8.0.3.nupkg 27ms
Installing Newtonsoft.Json 8.0.3.
Adding package 'Newtonsoft.Json.8.0.3' to folder 'F:\C# Development\Winform projects\UniversalSandbox\packages'
Added package 'Newtonsoft.Json.8.0.3' to folder 'F:\C# Development\Winform projects\UniversalSandbox\packages'
Added package 'Newtonsoft.Json.8.0.3' to 'packages.config'
Executing script file 'F:\C# Development\Winform projects\UniversalSandbox\packages\Newtonsoft.Json.8.0.3\tools\install.ps1'...
Successfully installed 'Newtonsoft.Json 8.0.3' to UniversalSandbox
========== Finished ==========
Now you'll be able to use Json.NET in your project easily.
Using JSON.NET
Primary, don't forget to include the respective use statement in the class that will handle JSON.
using Newtonsoft.Json;
Now see a collection of basic examples of JSON manipulation with C# (Serialize and Deserialize) :
Read JSON
Read a JSON string as you would do with XML files using JsonTextReader
and StringReader
(basic reading).
using Newtonsoft.Json;
using System.IO;
string json = @"{
'CPU': 'Intel',
'PSU': '500W',
'Drives': [
'DVD read/writer'
/*(broken)*/,
'500 gigabyte hard drive',
'200 gigabype hard drive'
]
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
{
if (reader.Value != null)
{
Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
}
else
{
Console.WriteLine("Token: {0}", reader.TokenType);
}
}
// Token: StartObject
// Token: PropertyName, Value: CPU
// Token: String, Value: Intel
// Token: PropertyName, Value: PSU
// Token: String, Value: 500W
// Token: PropertyName, Value: Drives
// Token: StartArray
// Token: String, Value: DVD read/writer
// Token: Comment, Value: (broken)
// Token: String, Value: 500 gigabyte hard drive
// Token: String, Value: 200 gigabype hard drive
// Token: EndArray
// Token: EndObject
Serialize a dynamic object (ExpandoObject) to JSON
Nothing is better than work with Javascript Objects is a pleasant experience as they're very dinamyc and allow you to do and save any kind of things. But, what would be better for a Javascript developer that work with dynamic objects in c#?.
The following example is most similar to write javascript in C# using an ExpandoObject
which allow you to add dinamically properties to an object, as javascript does.
Note: the serialization supports almost any kind of object, not only expando type.
using System.Dynamic;
dynamic myObject = new ExpandoObject();
myObject.name = "Our Code World";
myObject.website = "http://ourcodeworld.com";
myObject.language = "en-US";
List<string> articles = new List<string>();
articles.Add("How to manipulate JSON with C#");
articles.Add("Top 5: Best jQuery schedulers");
articles.Add("Another article title here ...");
myObject.articles = articles;
string json = JsonConvert.SerializeObject(myObject);
Console.WriteLine(json);
//{
// "name":"Our Code World",
// "website":"http://ourcodeworld.com",
// "language":"en-US",
// "articles":[
// "How to manipulate JSON with C#",
// "Top 5: Best jQuery schedulers",
// "Another article title here ..."
// ]
//}
Deserialize a JSON string to a partial class
You can read a JSON string and parse it into an existing c# class instead of read it property by property. Use the DeserializeObject
method.
The class in this case will be named SearchResult and it has the following structure :
public class SearchResult
{
public string Title { get; set; }
public string Content { get; set; }
public string Url { get; set; }
}
Now the code to process it should look like :
using Newtonsoft.Json.Linq;
string googleSearchText = @"{
'responseData': {
'results': [
{
'GsearchResultClass': 'GwebSearch',
'unescapedUrl': 'http://en.wikipedia.org/wiki/Paris_Hilton',
'url': 'http://en.wikipedia.org/wiki/Paris_Hilton',
'visibleUrl': 'en.wikipedia.org',
'cacheUrl': 'http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org',
'title': '<b>Paris Hilton</b> - Wikipedia, the free encyclopedia',
'titleNoFormatting': 'Paris Hilton - Wikipedia, the free encyclopedia',
'content': '[1] In 2006, she released her debut album...'
},
{
'GsearchResultClass': 'GwebSearch',
'unescapedUrl': 'http://www.imdb.com/name/nm0385296/',
'url': 'http://www.imdb.com/name/nm0385296/',
'visibleUrl': 'www.imdb.com',
'cacheUrl': 'http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com',
'title': '<b>Paris Hilton</b>',
'titleNoFormatting': 'Paris Hilton',
'content': 'Self: Zoolander. Socialite <b>Paris Hilton</b>...'
}
],
'cursor': {
'pages': [
{
'start': '0',
'label': 1
},
{
'start': '4',
'label': 2
},
{
'start': '8',
'label': 3
},
{
'start': '12',
'label': 4
}
],
'estimatedResultCount': '59600000',
'currentPageIndex': 0,
'moreResultsUrl': 'http://www.google.com/search?oe=utf8&ie=utf8...'
}
},
'responseDetails': null,
'responseStatus': 200
}";
JObject googleSearch = JObject.Parse(googleSearchText);
// get JSON result objects into a list
IList<JToken> results = googleSearch["responseData"]["results"].Children().ToList();
// serialize JSON results into .NET objects
IList<SearchResult> searchResults = new List<SearchResult>();
foreach (JToken result in results)
{
SearchResult searchResult = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
searchResults.Add(searchResult);
}
// List the properties of the searchResults IList
foreach (SearchResult item in searchResults)
{
Console.WriteLine(item.Title);
Console.WriteLine(item.Content);
Console.WriteLine(item.Url);
}
// Title = <b>Paris Hilton</b> - Wikipedia, the free encyclopedia
// Content = [1] In 2006, she released her debut album...
// Url = http://en.wikipedia.org/wiki/Paris_Hilton
// Title = <b>Paris Hilton</b>
// Content = Self: Zoolander. Socialite <b>Paris Hilton</b>...
// Url = http://www.imdb.com/name/nm0385296/
You can read more examples visiting the official documentation here. Have fun