Friday, December 14, 2007

Json.NET 1.1: Converting between XML and JSON

JAVASCRIPT:

1.

2.
XmlDocument doc = new XmlDocument();
3.
doc.LoadXml(@"
4.

5.

6.
Alan
7.
http://www.google.com
8.

9.

10.
Louis
11.
http://www.yahoo.com
12.

13.
");
14.

15.
string jsonText = JavaScriptConvert.SerializeXmlNode(doc);
16.
//{
17.
// "?xml": {
18.
// "@version": "1.0",
19.
// "@standalone": "no"
20.
// },
21.
// "root": {
22.
// "person": [
23.
// {
24.
// "@id": "1",
25.
// "name": "Alan",
26.
// "url": "http://www.google.com"
27.
// },
28.
// {
29.
// "@id": "2",
30.
// "name": "Louis",
31.
// "url": "http://www.yahoo.com"
32.
// }
33.
// ]
34.
// }
35.
//}
36.

37.
XmlDocument newDoc = (XmlDocument)JavaScriptConvert.DeerializeXmlNode(jsonText);
38.

39.
Assert.AreEqual(doc.InnerXml, newDoc.InnerXml);
40.

Json.NET - Simplifying .NET <-> JavaScript communication

JSON (JavaScript Object Notation) is lightweight data interchange format. In recent times JSON has achieved widespread use due to the ease of which it can be parsed and then the data accessed from within JavaScript compared to alternatives like XML.

While many JavaScript libraries exist for converting JSON text to and from a JavaScript object, working with JSON in .NET has been much more problematic. Correctly escaping strings and building up objects when writing JSON text can be difficult and error prone, while parsing values back out of JSON text is harder still.

Json.NET

Json.NET is a JSON .NET API for simply and safely reading and writing valid JSON text. At the core of Json.NET, similar to the .NET XML APIs, are two classes: JsonReader and JsonWriter. Also like XML in .NET, Json.NET includes a JsonSerializer class.

Reading JSON

JsonReader is a fast, forward only, readonly cursor. Like XmlTextReader it works over the top of a TextReader and maximizes performance while minimizing memory use.

The following code is a brief example of how to read a JSON object.

string jsonText = "['JSON!',1,true,{property:'value'}]";
 
JsonReader reader = new JsonReader(new StringReader(jsonText));
 
Console.WriteLine("TokenType\t\tValueType\t\tValue");
 
while (reader.Read())
{
    Console.WriteLine(reader.TokenType + "\t\t" + WriteValue(reader.ValueType) + "\t\t" + WriteValue(reader.Value))
}

Resulting in...

TokenType ValueType Value
StartArray null null
String System.String JSON!
Integer System.Int32 1
Boolean System.Boolean True
StartObject null null
PropertyName System.String property
String System.String value
EndObject null null
EndArray null null

Writing JSON

JsonWriter is also forward only, and writes JSON text to a TextWriter. It handles formatting numbers, escaping strings and validating that the object is valid.

The following code is a brief example of how to write a JSON object.

StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
 
writer.WriteStartArray();
writer.WriteValue("JSON!");
writer.WriteValue(1);
writer.WriteValue(true);
writer.WriteStartObject();
writer.WritePropertyName("property");
writer.WriteValue("value");
writer.WriteEndObject();
writer.WriteEndArray();
 
writer.Flush();
 
string jsonText = sw.GetStringBuilder().ToString();
 
Console.WriteLine(jsonText);
// ['JSON!',1,true,{property:'value'}]

Which prints out: ['JSON!',1,true,{property:'value'}].

Serializing and deserializing JSON and .NET objects

JsonSerializer, similar to XML serialization, provides a hassle free way to automatically convert .NET objects to and from JSON text.

The following code is a brief example of how to serialize and deserialize JSON and .NET objects.

string jsonText = "['JSON!',1,true,{property:'value'}]";
 
JsonSerializer serializer = new JsonSerializer();
 
JavaScriptArray jsArray = (JavaScriptArray) serializer.Deserialize(new JsonReader(new StringReader(jsonText)));
 
Console.WriteLine(jsArray[0]);
// JSON!
 
JavaScriptObject jsObject = (JavaScriptObject)jsArray[3];
 
Console.WriteLine(jsObject["property"]);
// value
 
StringWriter sw = new StringWriter();
 
using (JsonWriter jsonWriter = new JsonWriter(sw))
{
    serializer.Serialize(sw, jsArray);
}
 
Console.WriteLine(sw.GetStringBuilder().ToString());
// ['JSON!',1,true,{property:'value'}]

Json.NET - Json.NET Homepage

Download Json.NET - Json.NET dll and C# source code

Json.NET

The Json.NET library makes working with JavaScript and JSON formatted data in .NET simple. Quickly read and write JSON using the JsonReader and JsonWriter or serialize your .NET objects with a single method call using the JsonSerializer.

Json.NET CodePlex Project

Json.NET Download

Features

  • Lightning fast JsonReader and JsonWriter
  • The JsonSerializer for quickly converting your .NET objects to JSON and back again
  • Json.NET can optionally produce well formatted, indented JSON for debugging or display
  • Attributes like JsonIgnore and JsonProperty can be added to a class to customize how a class is serialized
  • Ability to convert JSON to and from XML

Example

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
 
string json = JavaScriptConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}
 
Product deserializedProduct = JavaScriptConvert.DeserializeObject<Product>(json);

History

Json.NET grew out of projects I was working on in late 2005 involving JavaScript, AJAX and .NET. At the time there were no libraries for working with JavaScript in .NET so I began to grow my own.

Starting out as a couple of static methods for escaping JavaScript strings, Json.NET evolved as features were added. To add support for reading JSON a major refactor was required and Json.NET will split into the three major classes it still uses today, JsonReader, JsonWriter and JsonSerializer.

Json.NET was first released in June 2006. Since then Json.NET has been downloaded thousands of times by developers and is used in a number of major projects open source projects such as MonoRail, Castle Project's MVC web framework, and Mono, an open source implementation of the .NET framework.

About Me

Ordinary People that spend much time in the box
Powered By Blogger