当前位置: 首页 > Web前端 > JSON > 正文

Json.NET

2018-04-24 来源:cnblogs/陈希章

简而言之,这是一个可以用于.NET的Json辅助工具类。它可以将对对象序列化为json字符串。下面是一个我自己写的用在ashx中的例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using System.Data;

namespace WebApplication1
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class GetData : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //var Employee = new { EmployeeName = "chenxizhang", Age = "20" };//直接构造一个简单的对象

            NorthwindDataContext db = new NorthwindDataContext();
            var orders = db.Orders.Where(o => o.OrderID <= 10250);//这是取得一系列对象

            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            string result = JsonConvert.SerializeObject(new { Orders = orders }, Formatting.Indented, settings);//需要注意的是,如果返回的是一个集合,那么还要在它的上面再封装一个类。否则客户端收到会出错的。
            context.Response.Write(result);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

image

在页面中使用jquery调用的方式如下

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="jqueryGetOrdersbyajax.aspx.cs" Inherits="WebApplication1.jqueryGetOrdersbyajax" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>通过ashx读取json数据,并显示订单信息</title>
    <% = minjquery %>
    <script language="javascript" type="text/javascript">

        var pageIndex = 0;
        $(function() {
            $.ajax(
        {
            type: "get",
            dataType: "json",
            url: "getdata.ashx",
            data: "pageIndex=" + pagecount,
            complete: function() { $("#load").hide(); },
            success: function(msg) {
                var data = msg.Orders;
                $.each(data, function(i, n) {
                    var row = $("#template").clone();
                    row.find("#OrderID").text(n.OrderID);
                    row.find("#CustomerID").text(n.CustomerID);
                    row.find("#EmployeeID").text(n.EmployeeID);
                    row.find("#OrderDate").text(ChangeDate(n.OrderDate));
                    if (n.ShippedDate !== undefined) row.find("#ShippedDate").text(ChangeDate(n.ShippedDate));
                    row.find("#ShippedName").text(n.ShipName);
                    row.find("#ShippedAddress").text(n.ShipAddress);
                    row.find("#ShippedCity").text(n.ShipCity);
                    row.find("#more").html("<a href=OrderInfo.aspx?id=" + n.OrderID + ">&nbsp;More</a>");
                    row.attr("id", "ready"); //改变绑定好数据的行的id
                    row.appendTo("#datas"); //添加到模板的容器中
                });
            }
        });
    });

    function ChangeDate(date) {
        return new Date(date);
    }

    </script>

</head>
<body>
<asp:PlaceHolder Visible="false" runat="server">
<script type="text/javascript" src="jquery-1.3.2-vsdoc.js"></script>
</asp:PlaceHolder>
    <div>
        &nbsp;<div>
            <br />
            <input id="first" type="button" value="  <<  " /><input id="previous" type="button"
                value="  <  " /><input id="next" type="button" value="  >  " /><input id="last" type="button"
                    value="  >>  " />
            &nbsp;<span id="pageinfo"></span>
            <table id="datas" border="1" cellspacing="0" style="border-collapse: collapse">
                <tr>
                    <th>
                        订单ID</th>
                    <th>
                        客户ID</th>
                    <th>
                        雇员ID</th>
                    <th>
                        订购日期</th>
                    <th>
                        发货日期</th>
                    <th>
                        货主名称</th>
                    <th>
                        货主地址</th>
                    <th>
                        货主城市</th>
                    <th>
                        更多信息</th>
                </tr>
                <tr id="template">
                    <td id="OrderID">
                    </td>
                    <td id="CustomerID">
                    </td>
                    <td id="EmployeeID">
                    </td>
                    <td id="OrderDate">
                    </td>
                    <td id="ShippedDate">
                    </td>
                    <td id="ShippedName">
                    </td>
                    <td id="ShippedAddress">
                    </td>
                    <td id="ShippedCity">
                    </td>
                    <td id="more">
                    </td>
                </tr>
            </table>
        </div>
        <div id="load" style="left: 0px; position: absolute; top: 0px; background-color: red">
            LOADING....
        </div>
        <input type="hidden" id="pagecount" />
    </div>
</body>
</html>