javascript
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);
}
);
</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;
}
}
{
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" }
}
};
}
?
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();
}
}
/// 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);
}
});
});
{
public void ProcessRequest(HttpContext context) {
DataEntity data = new DataEntity();
?
data.name = "Name";
data.value = 01;
context.Response.Write(data.JSONSerializer());
}
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);
}
});
});
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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: asp.net(C#)套用模板操作Exc
- 下一篇: CLR_via_C#.3rd 翻译[1.