|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionJavaScript Object Notation, or JSON, is meant as a light weight alternative to XML when XML is just a bit heavy weight for what you are trying to achieve. Although JSON is not extensible, as it makes use of a fixed set of data types, it can be used to textually represent complex objects. JSON is a perfect data-interchange format when using technologies such as AJAX as your server side objects can be converted to JSON, sent to the client, evaluated in a client script and then manipulated to build dynamic adverts, menus etc. Basic JSON StructureJSON is comprised of two structures that all programmers are famaliar with, namely:
JSON also defines four primtive types:
I don't want to bore you with the details, but links to the JSON specification can be found in the References section. The codeAll JSON types in the using System;
namespace NetServ.Net.Json
{
/// <summary>
/// Defines a JavaScript Object Notation data type.
/// </summary>
public interface IJsonType
{
/// <summary>
/// Writes the contents of the Json type using the specified
/// <see cref="NetServ.Net.Json.IJsonWriter"/>.
/// </summary>
/// <param name="writer">The Json writer.</param>
void Write(IJsonWriter writer);
/// <summary>
/// Gets the <see cref="NetServ.Net.Json.JsonTypeCode"/> of the type.
/// </summary>
JsonTypeCode JsonTypeCode {
get;
}
}
/// <summary>
/// Defines the different types of Json structures and primitives.
/// </summary>
[Serializable()]
public enum JsonTypeCode
{
/// <summary>
/// A unicode encoded string.
/// </summary>
String,
/// <summary>
/// A number.
/// </summary>
Number,
/// <summary>
/// A boolean value represented by literal "true" and "false".
/// </summary>
Boolean,
/// <summary>
/// A null value.
/// </summary>
Null,
/// <summary>
/// A structured object containing zero or more name/value pairs,
/// delimited by curly brackets.
/// </summary>
Object,
/// <summary>
/// An unordered collection of values, delimted by square brackets.
/// </summary>
Array
}
}
The using System;
namespace NetServ.Net.Json
{
/// <summary>
/// Defines a JavaScript Object Notation writer.
/// </summary>
public interface IJsonWriter
{
/// <summary>
/// Writes the start of an array to the underlying data stream.
/// </summary>
void WriteBeginArray();
/// <summary>
/// Writes the end of an array to the underlying data stream.
/// </summary>
void WriteEndArray();
/// <summary>
/// Writes the start of an object to the underlying data stream.
/// </summary>
void WriteBeginObject();
/// <summary>
/// Writes the end of an object to the underlying data stream.
/// </summary>
void WriteEndObject();
/// <summary>
/// Writes a object property name to the underlying data stream.
/// </summary>
/// <param name="value">The property name.</param>
void WriteName(string value);
/// <summary>
/// Writes a raw string value to the underlying data stream.
/// </summary>
/// <param name="value">The string to write.</param>
void WriteValue(string value);
}
}
Example of use within .NETHere is a short example of how to construct a collection of JSON types and write the result to the console. Please note that a more complex example, including multiple nested objects and arrays, is included in the demo project download. using System;
using NetServ.Net.Json;
namespace JsonTest
{
[STAThread()]
public class Program
{
public static void Main(string[] args) {
JsonObject order = new JsonObject();
JsonObject addr = new JsonObject();
JsonArray items = new JsonArray();
JsonObject item;
// Add some items into the array.
item = new JsonObject();
item.Add("ID", new JsonString("Chicken & Chips"));
item.Add("Qty", new JsonNumber(2));
item.Add("Price", new JsonNumber(1.50D));
item.Add("Req", new JsonString("Plenty of salad."));
items.Add(item);
// The less verbose way.
item = new JsonObject();
item.Add("ID", "Pizza");
item.Add("Qty", 1);
item.Add("Price", 9.60D);
item.Add("Size", "16\"");
item.Add("Req", "");
items.Add(item);
// Add the address information.
addr.Add("Street", "16 Bogus Street");
addr.Add("City", "Bogustown");
addr.Add("County", "Boguscounty");
addr.Add("Postcode", "B0GU5");
// Add the items and address into the order.
order.Add("Items", items);
order.Add("Address", addr);
order.Add("Name", "Andrew Kernahan");
order.Add("Tel.", "55378008");
order.Add("Delivery", true);
order.Add("Total", 12.60D);
using(JsonWriter writer = new JsonWriter()) {
// Get the container to write itself and all it's
// contained types to the writer.
order.Write(writer);
// Print the result.
Console.WriteLine(writer.ToString());
}
}
}
}
Using the {
"Items":
[
{
"ID": "Chicken & Chips",
"Qty": 2,
"Price": 1.5,
"Req": "Plenty of salad."
},
{
"ID": "Pizza",
"Qty": 1,
"Price": 9.6,
"Size": "16\"",
"Req": ""
}
],
"Address":
{
"Street": "16 Bogus Street",
"City": "Bogustown",
"County": "Boguscounty",
"Postcode": "B0GU5"
},
"Name": "Andrew Kernahan",
"Tel.": "55378008",
"Delivery": true,
"Total": 12.6
}
The using System;
using System.IO;
using NetServ.Net.Json;
namespace JsonTest
{
public class Program
{
[STAThread()]
public static void Main(string[] args) {
StringReader rdr =
new StringReader("{\"Name\":\"Andy\",\"Age\":23,\"Hungry?\":true}");
// The parser takes any TextReader derived class as its source.
JsonParser parser = new JsonParser(rdr, true);
JsonObject obj = (JsonObject)parser.ParseObject();
// Get the information from the object.
JsonString name = (JsonString)obj["Name"];
JsonNumber age = (JsonNumber)obj["Age"];
JsonBoolean hungry = (JsonBoolean)obj["Hungry?"];
// Print out the information.
Console.WriteLine("Name:\t\t{0}", name.Value);
Console.WriteLine("Age:\t\t{0}", age.Value.ToString());
Console.WriteLine("Hungry?:\t{0}", hungry.Value.ToString());
}
}
}
Example of use within JavaScriptIf you are using JSON as an AJAX data-interchange format, using the JSON text within a client side script couldn't be easier as the example below shows. function updateAdvertsCallback(result, context) {
// result = [
// {"AdvertId":"left","InnerHTML":"Some text","ImageSrc":"animage""},
// {"AdvertId":"right","InnerHTML":"Some more text",
// "ImageSrc":"anotherimage""}
// ]
// Use the JavaScript compiler to parse the text and generate
// the objects.
var adverts = eval("(" + result + ")");
// Then access the members as you would normally.
for(var i = 0; i < adverts.length; ++i) {
document.getElementById("advertHTML_" +
adverts[i].AdvertId).innerHTML = adverts[i].InnerHTML;
document.getElementById("advertImg_" +
adverts[i].AdvertId).src = adverts[i].ImageSrc;
}
}
You should be aware that JavaScript's Points of InterestMost of the JSON types in the // JsonBoolean jb = JsonBoolean.Get(true);
JsonBoolean jb = true;
// JsonNumber jn = new JsonNumber(42);
JsonNumber jn = 42;
// JsonString js = new JsonString("Hello World!");
JsonString js = "Hello World!";
Also the Unit TestsIncluded in the download are the unit tests compiled for the library. The tests were written in conjunction with Marc Clifton's Advanced Unit Testing tool. An overview of the two hundred tests can be seen below.
ConclusionI admit that this is a bit of a light weight article (please go easy as its my first!), but hopefully you will appreciate how useful the JSON format is when XML is just too much for your needs. References
Useful links
History
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||