首页 > 代码库 > 【c#】对象转json字符串/字符串转Json对象
【c#】对象转json字符串/字符串转Json对象
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)
【c#】对象转json字符串/字符串转Json对象
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。