【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)

 

posted @ 2016-11-08 11:45  Doc.stu  阅读(36092)  评论(3编辑  收藏  举报