C # convert JSON format to object type
Here I can only parse the situation where jsonstr = "{'name': 'Tom ', 'age': '11'}". If jsonstr = "{'name ': 'Tom ', 'age': '11'}, {'name': 'Tom', 'age': '11 '}",
I can't resolve it. Please give me some advice.
# Region C # parse JSON into object type (data can be read through Object Name point attribute name (convenient )) Public Void Jsontooo (){ String Jsonstr = " {'Name': 'Tom ', 'age': '11 '} " ; // Jsonstr is a JSON string Javascriptserializer JSON = New Javascriptserializer (); // Instantiate a class that can serialize data Tojson list = JSON. deserialize <tojson> (jsonstr ); // Convert JSON data to object type and assign it to list String Name = List. Name; // The value of name is Tom .. list, which indicates the name. } # Endregion # Region Intermediate object Public Struct Tojson { Public String Name { Get ; Set ;} // Attribute name, which must be the same as the "key" value in a JSON string. Public String Age { Get ; Set ;}} # Endregion
C # convert an object type to a JSON Data Format
Mainly parses the able read from the database (Cyclic conversion)
Note: add the following items to the project:System. Web. Extensions. dll
# Region Convert data to JSON format (mainly convert data in datatable to JSON format) Public Void Ootojson () {javascriptserializer JSON = New Javascriptserializer ();// Instantiate a class that can serialize data Tojson JSS = New Tojson (); // Here, JSS can be assigned cyclically. JSS. Age = " 11 " ; JSS. Name = " Lucy " ; String Jsonstr = JSON. serialize (JSS );// The jsonstr value is "{\" Name \ ": \" Lucy \ ", \" Age \ ": \" 11 \"}" } # Endregion # Region Intermediate object Public Struct Tojson { Public String Name { Get ; Set ;} // Attribute name, which must be the same as the "key" value in a JSON string. Public String Age { Get ; Set ;}} # Endregion
JS and jquery convert JSON format to object type
$ (Function (){ VaR Jsonstr = " [{\ "City \": \ "Beijing \", \ "street \": \ "Chaoyang Road \", \ "postcode \" :\ "100025 \"}, {\ "city \": \ "Shanghai \", \ "street \": \ "H \", \ "postcode \": \ "H \"}] " // JSON format VaR Jsons = $. parsejson (jsonstr ); // Jquery's. parsejson () method For ( VaR I = 0 ; I <jsons. length; I ++ ){ VaR JSON =Jsons [I]; alert (JSON. City ); // The result is output twice. }); Function (){ VaR Jsonstr = " [{\ "City \": \ "Beijing \", \ "street \": \ "Chaoyang Road \", \ "postcode \" :\ "100025 \"}, {\ "city \": \ "Shanghai \", \ "street \": \ "H \", \ "postcode \": \ "H \"}] " // JSON format VaR Jsons = eval (jsonstr ); // Eval () method of JS For ( VaR I = 0 ; I <jsons. length; I ++ ){ VaR JSON = Jsons [I]; alert (JSON. City ); // The result is output twice. }}