Monday, September 3, 2012

JSON for ASP.NET

We have seen that JSON text can easily be created and parsed from JavaScript code. Whenever JSON is used in ASP.NET web application, only browser part of the application used JavaScript since server side code is written in VB or C#.


There are many Ajax library designed for ASP.NET that provides support for programmatically creating and parsing JSON text. So we have to consider one of these libraries to work with JSON in a .net application. We will discuss about one library Jayrock. Jayrock is a modest and an open source (LGPL) implementation of JSON and JSON-RPC for the Microsoft .NET Framework, including ASP.NET.

Working with JSON in .NET using Jayrock is similar to working with XML through the XmlWriter, XmlReader, and XmlSerializer classes in the .NET Framework. There are some classes JsonWriter, JsonReader, JsonTextWriter and JsonTextReader used for interfacing with JSON at a low and stream oriented level. Using these classes. SON text can be created and parsed through a series of method calls. For example, using the JsonWriter class method WriteNumber(number) writes out the appropriate string representation of number according to the JSON standard. The JsonConvert class offers Export and Import methods for converting between .NET types and JSON. These methods provide a similar functionality as found in the XmlSerializer class methods Serialize and Deserialize, respectively.

Using Class JsonTextWriter
StringBuilder sbl=new StringBuilder();
StreamWriter swr = new StreamWriter(sbl);
JsonTextWriter writer = JsonTextWriter(swr);
writer.Formatting = Formatting.Indented;
writer.WriteStartObject();
writer.WritePropertyName("Job");
writer.WriteValue("Manager");
writer.WriteEndObject();
string output = sw.ToString();
writer.Close();
sw.Close();

Parsing JSON Text-Using Class JsonTextReader
The JsonTextReader class provides methods to parse the tokens of JSON text with the help of method Read. Each time the Read method is invoked, the parser consumes the next token, which could be a string value, a number value, an object member name, the start of an array, and so forth. Where applicable, the parsed text of the current token can be accessed via the Text property. For example, if the reader is sitting on Boolean data, then the Text property will return "true" or "false" depending on the actual parse value.

string jsonText = @"[""A"", ""B"", ""AC"", ""D"", ""E"", ""AF"", ""GA""]";
using (JsonTextReader reader = new JsonTextReader(new StringReader(jsonText)))
{
while (reader.Read())
{
if (reader.TokenClass == JsonTokenClass.String && reader.Text.StartsWith("A"))
{
Console.WriteLine(reader.Text);
}
}
}

No comments:

Copyright © Codingnodes,2014.All Rights Reserved.