码迷,mamicode.com
首页 > Windows程序 > 详细

【c#】对象转json字符串/字符串转Json对象

时间:2016-11-08 13:43:00      阅读:1319      评论:0      收藏:0      [点我收藏+]

标签:value   sof   strong   json   nbsp   soft   hash   console   style   

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对象

标签:value   sof   strong   json   nbsp   soft   hash   console   style   

原文地址:http://www.cnblogs.com/stgp/p/6029717.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!