日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JSON In Code

發布時間:2025/6/17 javascript 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JSON In Code 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

有關于定義,描述之類的文字官方都有解釋:http://json.org/json-zh.html

這次主題主要關于JSON的實際應用

?目錄

  • JSON in Javascript
  • JSON in Asp.Net
  • LINQ to JSON
  • JSON Serialization
  • XML to JSON
  • Other Resources

?

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;
}
}
}

轉載于:https://www.cnblogs.com/anmoon/archive/2010/08/26/1809467.html

總結

以上是生活随笔為你收集整理的JSON In Code的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。