C # parsing JSON-formatted data

Source: Internet
Author: User
Tags class definition serialization


JSON Brief Introduction

JSON (The full name is JavaScript objectnotation) is a lightweight data interchange format. It is based on a subset of JavaScript syntax standards. JSON is a completely language-independent text format that can be easily transmitted across networks, platforms, and programs. JSON's syntax is simple, easy to read and write, and also easy to machine parse and generate.

the comparison of JSON and XML

Readability

The readability of JSON and XML is compared to the fact that XML provides an auxiliary label that is more suitable for people to read and understand.

File size and transport

XML allows you to use convenient tags, so file sizes are larger than JSON. And JSON is derived from JavaScript, so the natural battlefield is JavaScript and the Web, where JSON has the advantage of being unable to catch up with XML.

JSON Syntax

1. The JSON syntax is a subset of the JavaScript object representation syntax.

Data in name/value pairs: The name is a string, expressed in double quotes. The values can be numeric (integer or floating-point), string (in double quotes), array (in square brackets), object (in curly braces), True/false/null.

Data is separated by commas:

Curly braces Save objects: objects can contain a variety of data, including arrays.

Square brackets Save an array: numbers can contain objects.

For example:

{'
   students ': [
       {
           ' name ': ' Coolszy ',
           ' age ': '
       },
       {
           ' name ': ' Kuka ',
           ' age ':
       '
    ]
}

2. If the JSON contains an escape character, you need to escape.

C # Operations JSON

The JSON file is read into memory as a string. NET operations JSON is the generation and parsing of JSON strings. There are usually several ways to manipulate JSON:

1. Original mode

Write your code directly to manipulate the JSON string according to the syntax format of JSON. If not necessary, few people should go this way and start over again.

2. General approach

This approach is to use the Open Source class library Newtonsoft.json (download address http://json.codeplex.com/). After downloading the project will be able to use. You can usually use Jobject, Jsonreader, jsonwriter processing. This is the most versatile and flexible way to change the unpleasant place at any time.

(1) Read the JSON string using Jsonreader:

String Jsontext =@ "{" "Input" ":" "Value" "," "Output" ":" "Result" "}";
Jsonreader reader = new JsonTextReader (Newstringreader (Jsontext));
while (reader. Read ())
{
   Console.WriteLine (reader). Tokentype + "\t\t" + reader. Valuetype+ "\t\t" + reader. Value);
}

(2) Write string using Jsonwriter:

StringWriter SW = new StringWriter ();
Jsonwriter writer = new JsonTextWriter (SW);
 
Writer. Writestartobject ();
Writer. Writepropertyname ("input");
Writer. WriteValue ("value");
Writer. Writepropertyname ("output");
Writer. WriteValue ("result");
Writer. Writeendobject ();
Writer. Flush ();
 
String Jsontext =SW. Getstringbuilder (). ToString ();
Console.WriteLine (Jsontext);

(3) using Jobject to read and write strings:

Jobject Jo = Jobject.parse (jsontext);
String[] Values =jo. Properties (). Select (item => item. Value.tostring ()). ToArray ();

(4) using Jsonserializer to read and write objects (based on Jsonwriter and Jsonreader):

Array-type data

String jsonArrayText1 = "[{' A ': ' A1 ', ' B ': ' B1 '},{' a ': ' A2 ', ' B ': ' B2 '}]";
Jarray ja = (jarray) jsonconvert.deserializeobject (JSONARRAYTEXT1);
String JA1A =ja[1]["a"]. ToString ();
or
jobject o = (jobject) ja[1];
String OA = o["a"]. ToString ();

Nested format

String jsontext = "{\ beijing\": {\ "zone\": \ "Haidian \", \ "zone_en\": \ "haidian\"}} ";
Jobject Jo = (jobject) jsonconvert.deserializeobject (jsontext);
String Zone =jo["Beijing" ["zone"]. ToString ();
String zone_en =jo["Beijing" ["Zone_en"]. ToString ();

Custom class Project

Project P = new Project () {Input = "stone", Output = "Gold"};
Jsonserializer serializer = Newjsonserializer ();
StringWriter SW = new StringWriter ();
Serializer. Serialize (Newjsontextwriter (SW), p);
Console.WriteLine (SW. Getstringbuilder (). ToString ());
 
StringReader sr = Newstringreader (@ "{" "Input" ":" "Stone" "," "Output" ":" "Gold" "}");
Project P1 = (project) serializer. Deserialize (new JsonTextReader (SR), typeof (Project));
Console.WriteLine (P1. Input + "=>" + p1. Output);

The above code is based on the following project class definition:

Class Project
{public
   string Input {get; set;}
   public string Output {get; set;}
}

In addition, if the above JsonTextReader and other classes are compiled, the description is our own modified class, replaced by your own related classes can be, do not affect the use.

3. Built-in mode

It is straightforward to serialize and deserialize objects using the JavaScriptSerializer class in the System.Web.Script.Serialization namespace provided in the. NET Framework 3.5/4.0.

Project P = new Project () {Input = "stone", Output = "Gold"};
 JavaScriptSerializer serializer = Newjavascriptserializer ();
 Varjson = serializer. Serialize (p);
 Console.WriteLine (JSON);
 
 VARP1 = serializer. Deserialize<project> (JSON);
 Console.WriteLine (P1. input+ "=>" + p1. Output);
 Console.WriteLine (ReferenceEquals (P,P1));

Note: If you are using VS2010, the target framework for the current project needs to be changed to the. Net Framework 4, and client profile cannot be used. Of course, this System.Web.Extensions.dll is mainly used by the Web, directly in the console project with a sense of waste of resources.

In addition, as you can see from the last sentence, serialization and deserialization are typical implementations of deep copies.

4. Contractual approach

Use the DataContractJsonSerializer or Jsonreaderwriterfactory implementation provided by System.Runtime.Serialization.dll.

Project P = new Project () {Input = "stone", Output = "Gold"};
DataContractJsonSerializer serializer = Newdatacontractjsonserializer (P.gettype ());
string Jsontext;
 
using (MemoryStream stream = Newmemorystream ())
{
   serializer. WriteObject (Stream, p);
   Jsontext = Encoding.UTF8.GetString (stream. ToArray ());
    Console.WriteLine (Jsontext);
}
 
using (MemoryStream ms = Newmemorystream (Encoding.UTF8.GetBytes (jsontext))
{
   DataContractJsonSerializer Serializer1 = Newdatacontractjsonserializer (typeof (Project));
   Project P1 = (project) serializer1. ReadObject (MS);
   Console.WriteLine (P1. Input + "=>" + p1. Output);
}


Notice here that the project class and the members need to add the relevant attribute:

[DataContract]
Class Project
{
   [DataMember] public
   string Input {get; set;}
   [DataMember]
   public string Output {get; set;}
}
 

Practical Reference:

JSON Verification Tool: http://jsonlint.com/

JSON Concise Tutorial: http://www.w3school.com.cn/json/

Newtonsoft.json class Library Download: http://json.codeplex.com/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.