您的位置:首页 > Web前端 > JavaScript

Json.net 的简单应用(个人随笔)

2012-06-15 15:46 260 查看
在接下来的项目中可能需要大量使用Json 所以就想到了Json.net 这个框架; 以前需要用json 都是自己拼接;这个有多笨就不多说了;

.net 自带的 Json库 不会用!!

所以一大早来 就去网上逛了一圈 下载了 json.net 4.0

写了一小段 测试一下 还OK的! 下面上代码

先把 Newtonsoft.Json.dll 引用进项目

然后添加 一个 ashx 文件 命名为 jsontest.ashx

代码如下:

<%@ WebHandler Language="C#" Class="jsontest" %>

using System;
using System.Web;
using System.Collections.Generic;
public class jsontest : IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";

Person info = new Person();
info.Name = "a";
info.Age = 18;
info.Birthday = Convert.ToDateTime("1988-05-03");
Person info1 = new Person();
info1.Name = "b";
info1.Age = 13;
info1.Birthday = Convert.ToDateTime("1988-05-20");

List<Person> list = new List<Person>();
list.Add(info);
list.Add(info1);

string json = Newtonsoft.Json.JsonConvert.SerializeObject(list);

context.Response.Write(json);
//return json;
}

public bool IsReusable {
get {
return false;
}
}

}

public class Person
{
public string Name { get; set; }

public int Age { get; set; }

[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime Birthday { get; set; }
}


上面这段代码就不多说了。

string json = Newtonsoft.Json.JsonConvert.SerializeObject(list);


这段就是 Json.net 转换成Json 的方法!

下面就是页面调用了,新建页面 命名为json.aspx

代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="json.aspx.cs" Inherits="test_json" %>

<!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 runat="server">
<title></title>
<script src="../inc/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../inc/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>

</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
// ashx 方法调用
$.ajax({
type: "post",
contentType: "application/json",
url: "jsontest.ashx",
data: {},
dataType: "json",
success: function (result) {
// var json = eval(data);
// alert(result[0].Name);
for (var i = 0; i < result.length; i++) {
document.writeln("Name" + i + "=" + result[i].Name + "<br/>Age" + i + "=" + result[i].Age + "<br/>Date" + i + "=" + result[i].Birthday + "<br/>");
}
}
});
});

</script>
</body>
</html>


然后运行结果



后来我又想到用Webservice 作为数据来源 于是

新建一个 webservice 命名为JsonService.asmx

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

/// <summary>
///JsonService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class JsonService : System.Web.Services.WebService {

public JsonService () {

//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}

[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public string Jsonstr()
{
Person info = new Person();
info.Name = "a";
info.Age = 18;
info.Birthday = Convert.ToDateTime("1988-05-03 12:12:12");
Person info1 = new Person();
info1.Name = "b";
info1.Age = 13;
info1.Birthday = Convert.ToDateTime("1988-05-20");

List<Person> list = new List<Person>();
list.Add(info);
list.Add(info1);

string json = JsonConvert.SerializeObject(list);

return json;
}

}

public class Person
{
public string Name { get; set; }

public int Age { get; set; }

[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime Birthday { get; set; }
}


页面 还是上面那个页面

但是遇到几个问题弄的我头大。。我一开始用ajax 基本之接发 aspx.cs 的没试过用webservice 所以。。。

下面只发 JS 代码:

一开始我写的和调用ashx 的方法一样

$.ajax({
type: "post",
contentType: "application/json",
// contentType: "application/json;utf-8",
url: "JsonService.asmx/Jsonstr",
data: "{}",
dataType: "json",
success: function (result) {
for (var i = 0; i < result.length; i++) {
document.writeln("Name" + i + "=" + result[i].Name + "<br/>Age" + i + "=" + result[i].Age + "<br/>Date" + i + "=" + result[i].Birthday + "<br/>");
}
}
});


显然是不对的 result.length 为 undefined 用firedebug 发现

result:    Object { d="[{"Name":"a","Age":18,"..."1988-05-20T00:00:00"}]"}


result 是这个结果。那么显然不对

后来把 result改成result.d

alert 出来 是那个json 串没错。。 于是又试下去

但是问题又来了打印出来 100多条数据而且 值都是 undefined 再调试看了一下。。result.d.length就为111

那么result.d这个值就不是 json 而是一个字符串

"[{"Name":"a","Age":18,"Birthday":"1988-05-03T12:12:12"},{"Name":"b","Age":13,"Birthday":"1988-05-20T00:00:00"}]"


又去网上搜了一下。发现要加一个转换 eval();
但是这个串直接这么转换还是不对。。后来找到原因了换成下面的 转换方式就正确了

var json = eval('(' + result.d + ')');


这个我也不知道是什么原理 反正弄出来了!

下面贴上正确的代码 顺便还调用了 默认的 Hello word

//  WebService 方法调用
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
url: "JsonService.asmx/HelloWorld",
data: {},
error: function () { alert("error"); },
success: function (result) {
alert(result.d);
//document.write(result.d);
}
});

$.ajax({
type: "post",
contentType: "application/json",
// contentType: "application/json;utf-8",
url: "JsonService.asmx/Jsonstr",
data: "{}",
dataType: "json",
success: function (result) {
//   alert(result.d);
var json = eval('(' + result.d + ')');
for (var i = 0; i < json.length; i++) {
document.writeln("Name" + i + "=" + json[i].Name + "<br/>Age" + i + "=" + json[i].Age + "<br/>Date" + i + "=" + json[i].Birthday + "<br/>");
}
}
});


学了第一步啊。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: