C # tutorial (CODE) on converting string to json object and json to object ),
C # tutorial on converting strings into json objects and json objects (CODE)
Using System. collections. generic; using Newtonsoft. json. linq; using Newtonsoft. json; using System. web. script. serialization; // convert string to json public static void strJson () {string jsonText = "{\" shenzheng \ ": \" Shenzhen \ ", \" beijing \": \ "Beijing \", \ "shanghai \": [{\ "zj1 \": \ "zj11 \", \ "zj2 \": \ "zj22 \"}, \ "zjs \"]} "; // convert to json object JObject jo = (JObject) JsonConvert. deserializeObject (jsonText); string zone = jo ["shenzheng"]. toString (); // output Shenzhen string zone_en = jo ["shanghai"]. toString (); // "[\ r \ n {\ r \ n \" zj1 \ ": \" zj11 \ ", \ r \ n \" zj2 \": \ "zj22 \" \ r \ n}, \ r \ n \ "zjs \" \ r \ n] "string zj1 = jo [" shanghai "] [1]. toString (); // "zjs" Console. writeLine (jo);} // convert objects and arrays to JSON public static void GetJsonString () {// initialize object Obj product = new Obj () {Name = "apple ", price = 5.5}; // serialized string o = new JavaScriptSerializer (). serialize (product); // value: "{\" Name \ ": \" Apple \ ", \" Price \ ": 5.5}" // convert an array to a json List
Products = new List
() {New Obj () {Name = "apple", Price = 5.5}, new Obj () {Name = "orange", Price = 2.5}, new Obj () {Name = "dried persimmon", Price = 16.00 }}; ProductList productlist = new ProductList (); productlist. getProducts = products; // serialized string OS = new JavaScriptSerializer (). serialize (productlist); // output "{\" GetProducts \ ": [{\" Name \ ": \" Apple \ ", \" Price \ ": 5.5 }, {\ "Name \": \ "orange \", \ "Price \": 2.5 },{ \ "Name \": \ "dry persimmon \", \ "Price \": 16}]} "} // convert json to object and array, deserialize public static void JSONStringToList () {// json string JsonStr = "{Name: 'apple', Price: 5.5}"; JavaScriptSerializer Serializer = new JavaScriptSerializer (); // convert the json string to an object, deserialization Obj obj = Serializer. deserialize
(JsonStr); Console. write (obj. name + ":" + obj. price + "\ r \ n"); // json string JsonStrs = "[{Name: 'apple', Price: 5.5}, {Name: 'orange ', price: 2.5 },{ Name: 'persimmon ', Price: 16}] "; JavaScriptSerializer Serializers = new JavaScriptSerializer (); // convert the json string into an array object and deserialize the List
Objs = Serializers. Deserialize
> (JsonStrs); foreach (var item in objs) {Console. Write (item. Name + ":" + item. Price + "\ r \ n ");}}