Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

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);
}
}
}

Sunday, September 2, 2012

JSON-Java Script Object Notation

Introduction
JSON is lightweight data interchange format. It is easy to understand and describe because it is a plain text. Since it is text format, hence language independent. It is much like XML but easier and faster. It uses conventions like C, C++, C #, Java, JavaScript and many other languages.

JSON is syntax for storing and exchanging text information like as XML.It is a subset of JavaScript. It uses JavaScript syntax for describing data objects, but is still language and platform independent. It is like XML because it is plain text and human readable, hierarchical and can be parsed by JavaScript.

The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.

JSON is built on two structures:
1. A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
2. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

JSON Syntax Rules

1. Data should be in pairs separated by colon (":")
For example, “Name":"Ravi”. This is similar to JavaScript syntax: Name="Ravi"
2. Data should be separated by comma (,)
For example, “Name":"Ravi”, “Phone":"9656757865","Age":"23"
3. Objects should be in curly brackets ("{}").
{"Name":"Ravi”, “Phone":"9656757865","Age":"23"}
4. array should be defined in square bracket("[]").
"information":{[{"Name":"Ravi”, “Phone":"9656757865","Age":"23"},
                       {"Name":"Javi","Phone":"7756757865","Age":"24"}
]}

JSON Values
JSON values can be a number or a string or a Boolean or an array or an object or null.

JSON Object
For example,
{"Name":"Ravi”, “Phone":"9656757865","Age":"23"}

JSON Array
{"information":{[{"Name":"Ravi","Phone":"9656757865","Age":"23"},

{"Name":"Javi","Phone":"7756757865","Age":"24"}
]}
};

Creating objects in JSON
Since JSON uses JavaScript syntax, will see how to create object in JSON
var object1={"information":[
{"Name":"Ravi”, “Phone":"9656757865","Age":"23"},
{"Name":"Javi","Phone":"7756757865","Age":"24"}
]
};
Here object1 is a object and information is a single member of it. Member bindings containing two objects each containing three members Name, Phone and Age.

 How to retrieve member of object?
In the given example, for retrieving member we can write

object1.information [0].Phone //we will get "9656757865"
object1.information [1].Age //we will get "24"

How to convert JSON text into a object?
Since JSON uses JavaScript syntax, method eval() is used for this. So to avoid ambiguity we prefer the text to be wrapped in parenthesis.
For example, var object2=eval ('(''+object1+)');
The eval function is very fast.However,it can compile and execute any JavaScript program, so there can be security issues. The use of eval is preferred when the source is trusted and competent. It is much safer to use JSON parser.

JSON Parser
In web applications over XMLHttpRequest, communication is permitted only to the same origin that provided the page, so it is trusted but it cannot be competent. If server is not rigorous in its JSON parser encoding or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleasing its malice.

To defend against this, a JSON parser should be used. A JSON parser will recognize only JSON text, rejecting all scripts. In browser that provides native JSON support, SON parsers are much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.
For example:
data1=JSON.parse (Object1, reviver);
Here reviver is a function that will be called for every key and value at every level of this final result. Each value will be replaced by the result of reviver function. This can be used to reform the generic objects into instances of pseudo classes or transform date string into date objects.

JSON Stringifier
It converts JavaScript data structure into JSON text.


Copyright © Codingnodes,2014.All Rights Reserved.