"C #" object to JSON string/string to JSON object

Source: Internet
Author: User
Tags string to json

Using Newtonsoft.json;

First, Hashtable to JSON

New Hashtable (); hash. ADD ("key1","val1"); hash. ADD ("key2","val2"); string json = Jsonconvert.serializeobject (hash); //{"Key1": "Val1", "Key2": "Val2"}
//of complex point structuresHashtable HASH1 =NewHashtable (); Hash1. ADD ("Hash1_key1","Hash1_val1"); Hash1. ADD ("Hash1_key2","Hash1_val2"); Hashtable Hash2=NewHashtable (); Hash2. ADD ("Hash2_key1","Hash2_val1"); Hash2. ADD ("Hash2_key2","Hash2_val2"); List<Hashtable> L_hash =NewList(); L_hash. ADD (HASH1); L_hash. ADD (HASH2); Hashtable Hash=NewHashtable (); hash. ADD ("List", L_hash);stringJSON =Jsonconvert.serializeobject (hash);//{"List": [{"Hash1_key2": "Hash1_val2", "Hash1_key1": "Hash1_val1"},{"Hash2_key2": "Hash2_val2", "Hash2_key1": " Hash2_val1 "}]}
// Front desk Use var obj = json.parse (JSON); Console.log (obj. list[0]["Hash1_key1"]); // Hash1_val1

Second, dictionary to JSON

dictionary<int,string> dic =Newdictionary<int,string>();d IC. ADD ("Key1","Val1");d IC. ADD ("Key2","Val2"); Jobject[] Jo= ( fromPinchDiCSelect NewJobject {NewJproperty ("Key", P.key),NewJproperty ("Val", P.value)}). Toarray<jobject>();stringJSON = Jsonconvert.serializeobject (JO);//{"dic": [{"Key": 1, "val": "Dic1"},{"key": 2, "Val": "Dic2"}]}

Third, string to JSON object

var str = "{\" key1\ ": \" value1\ ", \" key2\ ": \" Value2\ "}"; var jobj = json.parse (str); alert (jobj.key1); // Output: value1

Iv. JSON object to string

//obj as a JSON object var str = json.stringify (obj)

"C #" object to JSON string/string to JSON object

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.