json(http://www.asp.net/whitepapers/request-validation)

.net处理JSON简明教程

Json.Net是.net中的一种流行的高性能的JSON框架。

特点

  1. 灵活的JSON序列化转化.net对象为JSON字符串。和把JSON字符串转换为.net对象。
  2. 手动读写JSON的Linq to JSON
  3. 比.net内置的JSON序列化程序更高的性能和速度。
  4. 便于读写的JSON
  5. 从XML中读取或写入JSON
  6. 支持Silverlight和Windows phone.

    当你读写的JSON与.net类紧密关联时,JSON序列化程序是一个不错的选择。JSON序列化程序将自动读写相关类的JSON。

    如果你只对JSON里面的数据感兴趣、你没有与JSON相关联的.net类或者JSON数据与你的类没有任何关系,你需要从对象中手动读写数据。以上各种情况下,你可以使用LINQ To JSON. LINQ To JSON 允许你在.net中更容易的读取、写入、修改JSON数据。

    Download Json.NET from CodePlex or install using NuGet

    PM> Install-Package Newtonsoft.Json

    JSON.net下载地址列表

    http://json.codeplex.com/releases/view/74287

    提供JSON.NET 4.0 Release 3版本地址

    http://json.codeplex.com/releases/view/74287#DownloadId=287841

    更多JSON详细信息,请查看: http://james.newtonking.com/projects/json-net.aspx

    先构造一个简单的类employee

    Public class employee{

    Public string eid{get;set;}

    Public string ename{get;set;}

    Public string esex{get;set;}

    Public datetime birthday{get;set;}

    }

    JSON序列化与反序列化的方案

    1. 使用Json.Net 处理JSON序列化与反序列化

序列化方法

private string JsonSerialize(employee emp) {

return Newtonsoft.Json.JsonConvert.SerializeObject(emp);

}

反序列化方法

private employee JsonDeserialize(string json) {

return (employee)(Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(employee)));

}

  1. 使用JavaScriptSerializer进行序列化、反序列化

    序列化方法

private string JsonSerialize (employee emp) {

return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(emp);

}

反序列化

Private string JsonDeserialize (string json){

return (employee)(new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(json,typeof(employee)));

}

  1. 通过类DataContractJsonSerializer对JSON序列化和反序列化

    序列化方法

private string JsonSerialize (employee emp) {

System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs = newSystem.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(employee));

System.IO.MemoryStream ms = new System.IO.MemoryStream();

dcjs.WriteObject(ms, emp);

string json = System.Text.Encoding.UTF8.GetString(ms.ToArray());

ms.Close();

return json;

}

反序列化方法

private employee JsonDeserialize (string json) {

System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs = newSystem.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(employee));

System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));

employee obj = (employee)(dcjs.ReadObject(ms));

return obj;

}

  1. 通过Newtonsoft.Json.Linq.JObject获取JSON数据

private void LinqJson(string json) {

JObject obj = Newtonsoft.Json.Linq.JObject.Parse(json);

//获取全部数据值

foreach (JToken token in obj.Values()) {

Response.Write(token.ToString());

}

//获取唯一值

Response.Write(obj["eid"].ToString()+"<br />"); }

  1. 5、LINQ to JSON Example

string json = @"{

""Name"": ""Apple"",

""Expiry"": new Date(1230422400000),

""Price"": 3.99,

""Sizes"": [

""Small"",

""Medium"",

""Large""

]

}";

JObject o = JObject.Parse(json);

string name = (string)o["Name"];

// Apple

JArray sizes = (JArray)o["Sizes"];

string smallest = (string)sizes[0];

JSON序列化和反序列化日期时间的处理

JSON格式不直接支持日期和时间。DateTime值值显示为"/Date(700000+0500)/"形式的JSON字符串,其中第一个数字(在提 供的示例中为 700000)是 GMT 时区中自 1970  1  1 日午夜以来按正常时间(非夏令时)经过的毫秒数。该数字可以是负数,以表示之前的时间。示例中包括"+0500"的部分可选,它指示该时间属于Local 类型,即它在反序列化时应转换为本地时区。如果没有该部分,则会将时间反序列化为Utc

使用DataContractJsonSerializer的序列化方式对日期格式进行处理,其他的()序列化方案的使用方式是相同的。设计思想是通过正则表达式匹配,替换JSON里面的日期数据为正常的日期格式。

序列化方法

private string JsonSerialize (employee emp) {

System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs = newSystem.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(employee));

System.IO.MemoryStream ms = new System.IO.MemoryStream();

dcjs.WriteObject(ms, emp);

string json = System.Text.Encoding.UTF8.GetString(ms.ToArray());

ms.Close();

//替换JSON时间为字符串

string p = @"\\/Date\((\d+)\)\\/";

System.Text.RegularExpressions.MatchEvaluator me = new System.Text.RegularExpressions.MatchEvaluator(ConvertJsonDateToDataString);

System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(p);

json = regex.Replace(json, me);

return json;

}

private string ConvertJsonDateToDataString(System.Text.RegularExpressions.Match m) {

string result = string.Empty;

DateTime dt = new DateTime(1970,1,1);

dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));

dt = dt.ToLocalTime();

result = dt.ToString("yyyy-MM-dd HH:mm:ss");

return result;

}

反序列化方法

private employee JsonDeserialize (string json)

{

string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";

System.Text.RegularExpressions.MatchEvaluator me = new System.Text.RegularExpressions.MatchEvaluator(ConvertDateStringToJsonDate);

System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(p);

json = reg.Replace(json, me);

System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs=newSystem.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(employee));

System.IO.MemoryStream ms=new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));

employee emp=(employee)dcjs.ReadObject(ms);

return emp;

}

private string ConvertDateStringToJsonDate(System.Text.RegularExpressions.Match m)

{

string result = string.Empty;

DateTime dt = DateTime.Parse(m.Groups[0].Value);

dt = dt.ToUniversalTime();

TimeSpan ts = dt - DateTime.Parse("1970-1-1");

result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);

return result;

}

==========================================================================
这是一个可以用于.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;
}
}
}
}  

-----------------------

在页面中使用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> 

==========================
 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值