zoukankan      html  css  js  c++  java
  • 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;
    }
    }
    }
    赋予程序生命,还我自由河山!~ --CosMosGhost
  • 相关阅读:
    二叉树的遍历
    深度优先遍历和广度优先遍历
    N的阶乘末尾有多少个0
    框架产生的历史
    Ansible--初始ansible
    日积跬步05
    日积跬步04
    日积跬步03
    日积跬步02
    日积跬步01
  • 原文地址:https://www.cnblogs.com/anmoon/p/1809467.html
Copyright © 2011-2022 走看看