using Newtonsoft.Json;
一、Hashtable转Json
Hashtable hash = new Hashtable(); hash.Add("key1","val1"); hash.Add("key2","val2"); string json = JsonConvert.SerializeObject(hash);//{"key1":"val1","key2":"val2"}
//复杂点结构的 Hashtable hash1 = new Hashtable(); hash1.Add("hash1_key1", "hash1_val1"); hash1.Add("hash1_key2", "hash1_val2"); Hashtable hash2 = new Hashtable(); hash2.Add("hash2_key1", "hash2_val1"); hash2.Add("hash2_key2", "hash2_val2"); List<Hashtable> L_hash = new List<Hashtable>(); L_hash.Add(hash1); L_hash.Add(hash2); Hashtable hash = new Hashtable(); hash.Add("List", L_hash); string json = JsonConvert.SerializeObject(hash);//{"List":[{"hash1_key2":"hash1_val2","hash1_key1":"hash1_val1"},{"hash2_key2":"hash2_val2","hash2_key1":"hash2_val1"}]}
//前台使用 var obj = JSON.parse(json); console.log(obj.List[0]["hash1_key1"]);//hash1_val1
二、Dictionary转Json
Dictionary<int,string> dic = new Dictionary<int,string>(); dic.Add("key1","val1"); dic.Add("key2","val2"); JObject[] jo = (from p in dic select new JObject { new JProperty("key",p.Key),new JProperty("val",p.Value) }).ToArray<JObject>(); string json = JsonConvert.SerializeObject(jo);//{"dic":[{"key":1,"val":"dic1"},{"key":2,"val":"dic2"}]}
三、字符串转json对象
var str = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; var jobj = JSON.parse(str); alert(jobj.key1);//输出:value1
四、json对象转字符串
//obj为json对象var str = JSON.stringify(obj)
时间: 2024-10-21 02:27:09