Programming materials: C # simple parsing of JSON data examples with open source JSON parsing class

Source: Internet
Author: User

C # Parse JSON



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 "\". 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\t" + reader.ValueType + "\t\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/

Related Article

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.