有关于定义,描述之类的文字官方都有解释:http://json.org/json-zh.html
这次主题主要关于JSON的实际应用
目录
1.JSON in Javascript
单列表
<script>
var User = {"UserID":01, "Name":"Rico", "Email":"rico◎hotmail.com"};
alert(User.Name);
</script>
实际应用时,还可以把Name分为FirstName,LastName
{"UserID":01, "Name":{"FirstName":"Rico","LastName":"Rui"}, "Email":"rico◎hotmail.com"}
集合
<script>
var UserList = [
{"UserID":01, "Name":{"FirstName":"Rico","LastName":"Rui"}, "Email":"rico◎hotmail.com"},
{"UserID":02, "Name":{"FirstName":"XXX","LastName":"YYY"}, "Email":"xxx◎hotmail.com"},
{"UserID":03, "Name":{"FirstName":"ZZZ","LastName":"AAA"}, "Email":"YYY◎hotmail.com"}
];
alert(UserList[0].Name.FirstName);
</script>
2.JSON in Asp.Net
Home.aspx:
<script language="javascript" type="text/javascript">
$(function() {
$.getJSON("../WebForm1.aspx",
{ t: "json" },
function(o) {
alert(o.Name + "->" + o.Rating);
}
);
//以上写法也可以写成
///$.get("../WebForm1.aspx", {t:"json"}, function(o) { alert(o.Name + "->" + o.Rating); }, "json");
});
</script>
WebForm1.aspx.cs: (这里使用New Page方式,我们也可以使用httphandler方式(webForm1.ashx"))
using System.Web.Script.Serialization;
public partial class WebForm1 :System.Web.UI.Page {
protected void Page_Load ( object sender , EventArgs e ) {
JavaScriptSerializer jss = new JavaScriptSerializer ();
JSONClass jsonClass = new JSONClass ();
jsonClass.Name = "JSON";
jsonClass.Value = 1;
Response.ContentType = "text/plain";
Response.Write ( jss.Serialize ( jsonClass ) );
//必须收尾
Response.End ();
}
public class JSONClass {
public string Name;
public int Value;
}
}
3.LINQ to JSON (support in his Json.NET library)
创建数据
private class DataEntity
{
public string Title { get; set; }
public string Description { get; set; }
public IList<string> Categories { get; set; }
}
private List<DataEntity> SetDatas()
{
return new List<DataEntity>()
{
new DataEntity()
{
Title = "Title One",
Description = "Description One",
Categories = new List<string>() { "Json.NET", "LINQ" }
},
new DataEntity()
{
Title = "Title Two",
Description = "Description Two",
Categories = new List<string>() { "Json.NET", "CodePlex" }
}
};
}
public JObject SetDataToJObject(){
List<DataEntity> datas = SetDatas();
JObject rss =
new JObject (new JProperty ( "channel" ,
new JObject (new JProperty ( "title" , "Test Title" ) ,
new JProperty ( "description" , "Set Data Using JObject" ) ,
new JProperty ( "item" ,
new JArray (
from p in datas
orderby p.Title
select new JObject ( new JProperty ( "title" , p.Title ) ,
new JProperty ( "description" , p.Description ) ,
new JProperty ( "category" ,new JArray (
from c in p.Categories
select new JValue ( c ) )
)))))));
return rss.ToString ();
}
输出的结果
//{
// "channel": {
// "title": "Test Title",
// "description": "Set Data Using JObject",
// "item": [
// {
// "title": "Title Two",
// "description": "Description Two",
// "category": [
// "Json.NET",
// "CodePlex"
// ]
// },
// {
// "title": "Title One",
// "description": "Description One",
// "category": [
// "Json.NET",
// "LINQ"
// ]
// }
// ]
// }
//}
查询数据
public void SearchDataList() {
var dataList = SetDataToJObject();
var titles =
from p in dataList["channel"]["item"]
select p.Value<string> ( "title" );
foreach ( var item in titles ) {
Console.WriteLine ( item );
}
查询结果
//Title One
//Title Two
var categories =
from c in dataList["channel"]["item"].Children()["category"].Values<string> ()
group c by c into g
orderby g.Count () descending
select new { Category = g.Key , Count = g.Count () };
foreach ( var c in categories ) {
Console.WriteLine ( c.Category + " - Count: " + c.Count );
}
查询结果
//Json.NET - Count: 2
//LINQ - Count: 1
//CodePlex - Count: 1
}
*linq to Json 实际上就是linq to object
4.JSON Serialization
有关于序列化:
.NET Framewok 3.5也提供了JSON对象序列化和反序列化的类,System.Runtime.Serialization.Json 命名空间下的 DataContractJsonSerializer 类。
当然也可以使用JSon.Net中的Serializer
以下代码 使用DataContractJsonSerializer 类
定义实体
[DataContract]
public class DataEntity
{
[DataMember]
public String name { get; set; }
[DataMember]
public Int32 value { get; set; }
}
*Json 是在 Windows Communication Foundation (WCF) 中创建的 ASP.NET AJAX 服务所使用的默认数据格式。
所以定义实体会声明相关DataContract,DataMember的属性,
通过将 DataContract 附加到类并将 DataMember 属性附加到要序列化的成员,为DataEntity定义数据协定。
(反)序列化代码
/// <summary>
/// JSON序列化
/// </summary>
public string JSONSerializer(object item)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
serializer.WriteObject(memoryStream, item);
StringBuilder sb = new StringBuilder();
sb.Append(Encoding.UTF8.GetString(memoryStream.ToArray()));
return sb.ToString();
}
}
/// <summary>
/// JSON 反序列化为对象
/// </summary>
public T JSONDeSerializer<T>(string jsonStr)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr));
T jsonObj = serializer.ReadObject(memoryStream) as T;
memoryStream.Close();
return jsonObj;
}
序列化工作结束。以下演示如何
使用(反)序列化的数据或对象
获取数据 CODE—> Page
Page:
<script language="javascript" type="text/javascript">
$(function() {
$.ajax({
url: "WebForm2.ashx",
type: 'GET',
data: {},
dataType: 'json',
timeout: 1000,
error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus) },
success: function(result) {
alert(result.name + "->" + result.value);
}
});
});
</script>
CodeFile:
public class WebForm2: IHttpHandler
{
public void ProcessRequest(HttpContext context) {
DataEntity data = new DataEntity();
data.name = "Name";
data.value = 01;
context.Response.Write(data.JSONSerializer());
}
public bool IsReusable {
get
{
return false;
}
}
}
返回结果
{"name":"Name","value":01}
设置数据 Page—>Code
Page:
<script src="json2.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(function() {
var jsData = { name: "Name", value: 01 };
//应用Json2.js中的stringify方法生成JSon String
var jsonStr = JSON.stringify(jsData);
$.ajax({
url: "WebForm3.ashx",
type: 'POST',
data: { postjson: jsonStr },
dataType: 'json',
timeout: 1000,
error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus) },
success: function(result) {
alert(result.success);
}
});
});
</script>
CodeFile:
public class webForm3: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string jsonStr = context.Request["postjson"];
DataEntity dataEntity = jsonStr.JSONDeSerializer<DataEntity>();
if (string.IsNullOrEmpty(dataEntity.name))
{
context.Response.Write("{success:false}");
}
else
{
context.Response.Write("{success:true}");
}
}
public bool IsReusable {
get
{
return false;
}
}
}
5.XML to JSON
参考:xml2json
6.其他资源:
1.Enum
首先所有 enum 成员都是可序列化的,然后序列化Enum值时,一般只会生成数字
如:public enum Color {red, green, blue, yellow, pink},则序列化 yellow 将生成数字 3,而不是字符串“yellow”。
2.Time、Date
JSON 格式不直接支持日期和时间,为了解决问题微软也有处理方案,如下
资源参考:
微软ASP.NET AJAX中日期类型的JSON处理
Json 的日期格式与.Net DateTime类型的转换
代码:
Code File:
public class Data {
public string Name;
public DateTime time;
}
public String getData() {
Data pd = new Data ("Rico", DateTime.Now());
return "(" + JavascriptSerializer.Serializer(pd) + ")";
}
Page:
<script language="javascript" type="text/javascript">
var pagedata = eval('<%= getData() %>');
</script>
3.JsonCache