C # How to parse JSON files

Source: Internet
Author: User

C # AnalysisJSON

JSON (fully called JavaScript Object Notation) is a lightweight data exchange format. It is a subset based on JavaScript syntax standards. JSON is in a language-independent text format and can be easily transmitted between various networks, platforms, and programs. The JSON syntax is simple, easy for reading and writing, and easy for machine parsing and generation.

Comparison between JSON and XML
◆ Readability
Compared to the readability of JSON and XML, XML provides auxiliary labels, which are more suitable for reading and understanding.
◆ File size and transmission
XML allows easy-to-use labels, so the file size is larger than JSON. JSON is derived from JavaScript, so JavaScript and the network are the natural battlefield. Here, JSON has the advantage that XML cannot catch up.

JSON syntax
1. JSON syntax is a subset of the syntax of JavaScript Object Notation.

  • Data in name/value pairs: The name is a string, expressed in double quotation marks. The value can be a number (integer or floating point number), a string (in double quotation marks), an array (in square brackets), an object (in curly brackets), true/false/null.
  • Data are separated by commas:
  • Brackets save objects: objects can contain various types of data, including arrays.
  • Square brackets save an array: numbers can contain objects.

For example:

{
"Employees ":[
{
"Firstname": "bill ",
"Lastname": "Gates"
},
{
"Firstname": "George ",
"Lastname": "Bush"
}
]
}

2. If JSON contains escape characters, escape is required. For example, you must use "\" instead of "\" in the file path "\". For example: {"file": "C: \ a.txt "}.

 

. Net JSON operation
The JSON file is read into the memory as a string, and The. Net Operation JSON is to generate and parse the JSON string. JSON operations can be performed in the following ways:
1. Original Method: Write code to directly operate the JSON string according to the JSON syntax format. Unless necessary, few people should follow this path and start from scratch.

2. General method 【★★★★★]:

This approach is to use the open source class library newtonsoft. JSON (http://json.codeplex.com /). After the download, add the project to use it. Generally, jobject, jsonreader, and jsonwriter can be used for processing. This method is the most common and flexible, and can be modified at any time.
(1) Use jsonreader to read JSON strings:

String jsontext = @ "{" "input" ":" "value" "," "output" ":" "result ""}";
Jsonreader reader = new jsontextreader (New stringreader (jsontext ));

While (reader. Read ())
{
Console. writeline (reader. tokentype + "\ t" + reader. valuetype + "\ t" + reader. value );
}

(2) Use jsonwriter to write strings:

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) Use 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 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 Project

Project P = new project () {input = "Stone", output = "gold "};
Jsonserializer serializer = new jsonserializer ();
Stringwriter Sw = new stringwriter ();
Serializer. serialize (New jsontextwriter (SW), P );
Console. writeline (SW. getstringbuilder (). tostring ());

Stringreader sr = new stringreader (@ "{" "input" ":" "Stone" "," "output" ":" gold ""}");
Project p1 = (Project) serializer. deserialize (New jsontextreader (SR), typeof (Project ));
Console. writeline (p1.input + "=>" + p1.output );

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

Class project
{
Public String input {Get; set ;}
Public String output {Get; set ;}
}

In addition, if the above jsontextreader and other classes cannot be compiled, it indicates that it is the class we have modified. you can replace it with your own related classes without affecting usage.

3. built-in Methods: Use the javascriptserializer class in the system. Web. Script. serialization namespace provided in. NET Framework 3.5/4.0 to serialize and deserialize objects directly.

Project P = new project () {input = "Stone", output = "gold "};
Javascriptserializer serializer = new javascriptserializer ();
VaR JSON = serializer. serialize (P );
Console. writeline (JSON );

VaR p1 = serializer. deserialize <project> (JSON );
Console. writeline (p1.input + "=>" + p1.output );
Console. writeline (referenceequals (p, P1 ));

Note:If vs2010 is used, the target framework of the current project must be changed to. NET Framework 4, and the client profile cannot be used. Of course, this system. Web. Extensions. dll is mainly used by the web, and it feels a waste of resources to be used directly in the console project.
In addition, you can see from the last sentence,Serialization and deserialization are typical implementations of deep copy..

4. Contract Mode: Use the datacontractjsonserializer or jsonreaderwriterfactory provided by system. runtime. serialization. dll.

Project P = new project () {input = "Stone", output = "gold "};
Datacontractjsonserializer serializer = new datacontractjsonserializer (P. GetType ());
String jsontext;

Using (memorystream stream = new memorystream ())
{
Serializer. writeobject (stream, P );
Jsontext = encoding. utf8.getstring (stream. toarray ());
Console. writeline (jsontext );
}

Using (memorystream MS = new memorystream (encoding. utf8.getbytes (jsontext )))
{
Datacontractjsonserializer serializer1 = new datacontractjsonserializer (typeof (Project ));
Project p1 = (Project) serializer1.readobject (MS );
Console. writeline (p1.input + "=>" + p1.output );
}

Note that the project class and members must 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/

Original article: http://www.cnblogs.com/txw1958/archive/2012/08/01/csharp-json.html

 

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.