C # process JSON files

Source: Internet
Author: User
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 used on various networks, platforms, and Program . The JSON syntax is simple, easy for reading and writing, and easy for machine parsing and generation. Comparison between JSON and XML ◆ Readability: Compared with XML, XML provides auxiliary labels, which is more suitable for reading and understanding. ◆ File size and transfer XML allow easy-to-use labels, so the file size is larger than that of 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 JavaScript Object Notation syntax. • 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 Arrays: numbers can contain objects. For example: {"employees": [{"firstname": "bill", "lastname": "Gates" },{ "firstname": "George", "lastname ": "Bush"}]} copy Code 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 "}. The. Net Operation JSON file is read into the memory as a string, and The. Net Operation JSON is to generate and parse the JSON string. The following methods are usually used to operate JSON: 1. original method: write code to directly operate JSON strings according to the JSON syntax format. Unless necessary, few people should follow this path and start from scratch. 2. General approach: This approach uses 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);} copy the code (2) use jsonwriter to write the string: stringwriter Sw = new stringwriter (); jsonwriter writer = new jsontextwriter (SW); writer. writestartobje CT (); writer. writepropertyname ("input"); writer. writevalue ("value"); writer. writepropertyname ("output"); writer. writevalue ("result"); writer. writeendobject (); writer. flush (); string jsontext = Sw. getstringbuilder (). tostring (); console. writeline (jsontext); copy code (3) Use jobject to read and write strings: jobject Jo = jobject. parse (jsontext); string [] values = Jo. properties (). select (item => item. value. tostring ()). toarray (); copy code (4) use Jsonserializer read and write objects (based on jsonwriter and jsonreader): 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) se Rializer. deserialize (New jsontextreader (SR), typeof (Project); console. writeline (p1.input + "=>" + p1.output); copy the code. The above Code is based on the following project class definition: class project {Public String input {Get; set ;} public String output {Get; Set ;}} copies the Code. In addition, if the above jsontextreader and other classes cannot be compiled, it indicates that they are our own modified classes, you can switch to your own related classes without affecting the usage. 3. built-in method: Use the javascriptserializer class in the. NET Framework 3.5/4.0 system. Web. Script. serialization namespace 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); copy the code. Note: If vs2010 is used, change the target framework of the current project. NET framework 4, cannot use Client Profile. 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, we can see from the last sentence that serialization and deserialization are a typical Implementation Method 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);} copy the code. Note that attribute must be added to the project class and members: [datacontract] class project {[datamember] Public String input {Get; set;} [datamember] Public String output {Get; Set ;}} copy the Code. For details, refer to JSON verification tool: bytes/

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.