C parses the implementation code for the json file

  • 2020-05-12 03:13:55
  • OfStack

C # parse json

JSON(fully known as JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of the JavaScript grammar standard. JSON is a completely language-independent text format that can be easily transferred between a variety of networks, platforms, and programs. The syntax of JSON is simple, easy for people to read and write, and easy for machines to parse and generate.

Comparison of JSON and XML

Readability in pieces
Compared with the readability of JSON and XML, XML is more suitable for people to read and understand because it provides auxiliary labels.
◆ file size and transfer
XML allows easy tagging, so the file size is larger than JSON. Moreover, JSON is derived from Javascript, so the natural main battlefield is Javascript and network, where JSON has an advantage that XML cannot surpass.

JSON grammar

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

The & # 8226; The data is in the name/value pair: the name is a string, 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 braces), true/false/null.
The & # 8226; Data separated by commas:
The & # 8226; Curly braces hold objects: objects can contain a variety of data, including arrays.
The & # 8226; Square brackets hold arrays: Numbers can contain objects.

Such as:


{
    "employees": [
        {
            "firstName": "Bill",
            "lastName": "Gates"
        },
        {
            "firstName": "George",
            "lastName": "Bush"
        }
    ]
}

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

NET JSON operation

The JSON file is read into memory as a string, and the.NET operation JSON is to generate and parse the JSON string. JSON can be operated in the following ways:

1. Original mode: write code to directly manipulate JSON string in accordance with the grammatical format of JSON. If it is not necessary, few people will go down this road and start all over again.

2. General mode 【★★★ 】 :

This way is to use open source libraries Newtonsoft. Json (download address http: / / json. codeplex. com /). Download and add to the project. You can usually use JObject, JsonReader, JsonWriter. It's the most versatile and flexible way to change what you don't like.
(1) read Json string using JsonReader:


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) write a 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) read and write strings with JObject:


JObject jo = JObject.Parse(jsonText);
string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray(); 

(4) read and write objects using JsonSerializer (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 class 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 based on the 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, it means that we have modified the class, but you can replace it with your own related class, which does not affect the use.

. 3. The built-in way: use NET Framework System. Available in 3.5/4.0 Web. Script. Serialization JavaScriptSerializer class under the namespace object serialization and deserialization, very direct.


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, Target Framework for the current project is required to be changed to.Net Framework 4, not Client Profile. . Of course the System Web. Extensions. dll is primarily Web use, directly in Console engineering by feeling a little waste of resources.

In addition, as you can see from the last sentence, serialization and deserialization are a typical implementation of deep copy.

4. Contract way: use System. Runtime. Serialization. dll provide DataContractJsonSerializer or JsonReaderWriterFactory implementation.


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 here that the Project class and members are associated with Attribute:


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);
}
0

Practical reference:
JSON validation tool: http: / / jsonlint com /
JSON introductory tutorial: / / www. ofstack. com/w3school/json /
Download Newtonsoft. Json libraries: http: / / json codeplex. com /


Related articles: