C # Methods for parsing JSON files

Source: Internet
Author: User
Tags object serialization

C # parsing JSON


JSON (the full name of JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of the JavaScript syntax standards. JSON is a completely language-independent text format that can easily be transferred between various networks, platforms, and programs. The syntax of JSON is simple, easy to read and write, and easy to machine parse and generate.

Comparison of JSON and XML
Readability
Compared to the readability of JSON and XML, XML provides an accessible label, which is more suitable for people to read and understand.
File size and Transfer
XML allows easy-to-use tags, so file sizes are larger than JSON. And JSON comes from JavaScript, so the natural battlefield is JavaScript and the Web, where JSON has the advantage of not being able to catch up with XML.

JSON syntax
1. JSON syntax is a subset of JavaScript object notation syntax.

    • The data is in a name/value pair: The name is a string and is represented by double quotation marks. Values can be: numbers (integers or floating-point numbers), strings (in double quotes), arrays (in square brackets), objects (in curly brackets), true/false/null.
    • Data is separated by commas:
    • Curly braces Save objects: objects can contain various 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 the JSON contains escape characters, you need to escape. For example, you need to use "\ \" instead of "\" in the file path. For example: {"file": "C:\\a.txt"}.

. NET Operation JSON
The JSON file is read into memory as a string. NET operation JSON is the generation and parsing of JSON strings. There are usually several ways to manipulate JSON:
1. Original Way : In accordance with the JSON syntax format, write code directly manipulate the JSON string. If not necessary, few people should go this way and start over again.

2. Common mode "★★★★★":

This approach is to use Open source class library Newtonsoft.json (http://json.codeplex.com/). After downloading, you can use it to join the project. You can usually use Jobject, Jsonreader, jsonwriter processing. This is the most versatile, and the most flexible, you can change the uncomfortable place at any time.
(1) Use Jsonreader to read the JSON string:

string @" {"Input" ":" "Value" "," "Output" ":" "Result" "} "  New jsontextreader (new  StringReader (Jsontext));  while (reader. Read ()) {    "\t\t""\t\t" + reader. Value);}

(2) write a string using Jsonwriter:

StringWriter SW =NewStringWriter (); Jsonwriter writer=NewJsonTextWriter (SW); writer. Writestartobject (); writer. Writepropertyname ("input"); writer. WriteValue ("value"); writer. Writepropertyname ("Output"); writer. WriteValue ("result"); writer. Writeendobject (); writer. Flush ();stringJsontext =SW. Getstringbuilder (). ToString (); Console.WriteLine (jsontext);

(3) Read and write strings using Jobject:

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) jsonconvert.deserializeobject (JSONARRAYTEXT1);  string  ja1a = Ja[ " a  "   //  or  Jobject o = (jobject) ja[";  string  oa = O[ " a   "]. ToString (); 

Nested formats

stringJsontext ="{\ "beijing\": {\ "zone\": \ "Haidian \", \ "zone_en\": \ "Haidian\"}}"; Jobject Jo=(Jobject) jsonconvert.deserializeobject (jsontext);stringZone = jo["Beijing"]["Zone"]. ToString ();stringZone_en = jo["Beijing"]["zone_en"]. ToString ();

Custom class Project

Project p =NewProject () {Input ="Stone", Output ="Gold" }; Jsonserializer Serializer=NewJsonserializer (); StringWriter SW=NewStringWriter (); serializer. Serialize (NewJsonTextWriter (SW), p); Console.WriteLine (SW. Getstringbuilder (). ToString ()); StringReader SR=NewStringReader (@"{"Input" ":" "Stone" "," "Output" ":" "Gold" "}"); Project P1= (Project) serializer. Deserialize (NewJsonTextReader (SR),typeof(Project)); Console.WriteLine (P1. Input+"="+ P1. Output);

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

class project{    publicstringgetset;}      Public string Get Set ; }}

In addition, if the above JsonTextReader and other classes 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 : Using the. NET Framework 3.5/ The JavaScriptSerializer class in the System.Web.Script.Serialization namespace provided in 4.0 is a straightforward object serialization and deserialization.

Project p =NewProject () {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, you are required to change the target Framework of the current project to. Net Framework 4, and you cannot use client profile. Of course, this System.Web.Extensions.dll is mainly used by the Web, directly in the console project with a feeling a little waste of resources.
In addition, it can be seen from the last sentence that serialization and deserialization are typical implementations of deep copies .

4. Contract method : Using DataContractJsonSerializer or jsonreaderwriterfactory provided by System.Runtime.Serialization.dll.

Project p =NewProject () {Input ="Stone", Output ="Gold"};D Atacontractjsonserializer Serializer=NewDataContractJsonSerializer (P.gettype ());stringJsontext;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);}

Note here that the project classes and Members here are related to the attribute:

[DataContract] class project{    [DataMember]    publicstringgetset;    [DataMember]      Public string Get Set ; }}

C # Methods for parsing JSON files

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.