!用对象生成JSON串
用对象组建JSON数据可很好地避免拼接字符串的困扰,如符号或多或少造成整个字符串不是合法的JSON串。
下面以生成如下JSON串为例介绍代码示例:
{
"a1": "1",
"a2": "2",
"a3": [
{
"b1": "3",
"b2": "4"
},
{
"b1": "5",
"b2": "6"
}
],
"a4": [
"7",
"8"
]
}
!!%second%C#版
下载源代码:http://downloads.cmcloud.cn/kis/kis_src/code/Json_CSharp_VS2010.rar
!!%second%生成JSON方法1:用JavaScriptSerializer(微软自带的)
'''引用.net组件:System.Web.Extensions'''
'''using System.Web.Script.Serialization;'''
'''using System.Collections;'''
private string createJsonString1() {
String sJson = "";
Hashtable htroot = new Hashtable();
List<Hashtable> lst = null;
List<String> lststr = null;
Hashtable ht = null;
htroot.Add("a1", "1");
htroot.Add("a2", "2");
lst = new List<Hashtable>();
ht = new Hashtable();
ht.Add("b1", "3");
ht.Add("b2", "4");
lst.Add(ht);
ht = new Hashtable();
ht.Add("b1", "5");
ht.Add("b2", "6");
lst.Add(ht);
htroot.Add("a3", lst);
lststr = new List<String>();
lststr.Add("7");
lststr.Add("8");
htroot.Add("a4", lststr);
JavaScriptSerializer jss = new JavaScriptSerializer();
sJson = jss.Serialize(htroot);
return sJson;
}