Use the 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) Use 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 ja = (jarray) jsonconvert.deserializeobject (JSONARRAYTEXT1); string ja1a = ja[1]["a"]. ToString ();//or Jobject o = (jobject) ja[1];string OA = o["a"]. ToString ();
Nested formats
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 code above is based on the following project class definition:
Class Project
{
public string Input {get; set;}
public string Output {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.
Bill: How C # operates JSON data (read, parse)