一:定义
1. "名称/值"对的集合(名称为字符串类型,值可以是字符串,整数,对象等任意类型)
2. 值的有序列表(array)
二:实例,javascript中的json
1)简单的json
var User = {"UserID":11, "Name":"Truly", "Email":"zhuleipro◎hotmail.com"};
alert(User.Name);
2)值的有序列表(array)
var userAry= [
{"subject":"New Draft","senddate":"2008-11-12 17:44","id":"3337","from":"liuyan1@chinahr.com"},
{"subject":"New Draft","senddate":"2008-11-12 17:44","id":"3336","from":"liuyan1@chinahr.com"},
{"subject":"New Draft","senddate":"2008-11-12 17:44","id":"3335","from":"liuyan1@chinahr.com"}
]
alert(userAry.length);
alert(userAry[0].id);
alert(userAry[0]["id"]);
3)复杂的json
var tt={
"length":{"length":3},
"a":{"subject":"New Draft","senddate":"2008-11-12 17:44","id":3337,"from":"liuyan1@chinahr.com"},
"1":{"subject":"New Draft","senddate":"2008-11-12 17:44","id":3336,"from":"liuyan1@chinahr.com"},
"2":{"subject":"New Draft","senddate":"2008-11-12 17:44","id":3335,"from":liuyan1@chinahr.com}
}
alert(tt.length.length);
alert(tt["a"].id);
alert(tt[1].id)
///
输出的JSON字符串里如果有引号,单引号和反斜杠前面加反斜杠“\”如:
string s="a\\\"b\\\"c d";
Response.Write("{\"text\":\""+s+"\"}" );
.net2.0使用Json调用
using System.Runtime.Serialization.Json;
DataTable转化成json字符串,去除单引号双引号的问题
private DataTable getDataTable(string name)
{
DataTable dt = new DataTable(name);
dt.Columns.Add(new DataColumn("name", typeof(string)));
dt.Columns.Add(new DataColumn("password", typeof(string)));
DataRow dr;
for (int i = 0; i < 3; i++)
{
dr = dt.NewRow();
dr[0] = i.ToString();
dr[1] = "P" + i.ToString();
dt.Rows.Add(dr);
}
string ss = "dddd' ddddd";
dr = dt.NewRow();
dr[0] = ss;
dr[1] = "hh";
dt.Rows.Add(dr);
return dt;
}
private string DataTable2Json(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i != 0) { jsonBuilder.Append(","); }
jsonBuilder.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("\'");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("\':\'");
jsonBuilder.Append(dt.Rows[i][j].ToString().Replace("\"","").Replace("\'",""));
jsonBuilder.Append("\',");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("}");
}
jsonBuilder.Append("]");
return jsonBuilder.ToString();
}