C # parse Json data,

Source: Internet
Author: User

C # parse Json data,

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

 

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.