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

C#学习笔记-C#中Json.Net(newtonjs)的使用

2017-08-19 14:44 453 查看
首先简单了解一下newtonjson。假设有一个MVC项目,传统向前台传输一个Json的数据,比如一个DateTime日期类型,在前台输出后可能会显示成一堆很乱的数字格式,比如"/Date(1503125172800)/",程序员看到这一串很乱糟糟的结果会觉得头晕,虽然微软官方解释有其他方法可以将这个解析成正确的日期格式,但也显得很麻烦。实际上,有更好的方法避免这样的情况发生。也就是Json.Net(newtonjs),这是.Net中使用频率非常高的Json库。

一、传统方式下的Json向前台传输数据的操作

1.新建MVC项目,在Models文件夹中添加实体类Person.cs,详细代码如下:

public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime BirthDate { get; set; }//出生日期
}
2.添加控制器DefaultController,在控制器中增加两个有重载关系的action。action的名字都是TestJson,详细代码如下:

[HttpGet]
public ActionResult TestJson()
{
return View();
}

[HttpPost]
public ActionResult TestJson(FormCollection fc)
{
Person per = new Person() { BirthDate = DateTime.Now, Id = 5, Name = "大古" };
return Json(Person);
}
注意:这里的FormCollection fc在本次练习中没有任何意义,只是为了让两个方法构成重载。熟悉[HttpGet]和[HttpPost]用法的应该知道这里构成重载的好处是什么,这里就不做详细解释了。

3.新增视图TestJson.cshtml,给视图引入jquery-1.8.3.js文件,因为需要用到ajax来提交和接收数据。重要代码如下:

<script src="~/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function () {
$("#btn1").click(function () {
$.ajax({
url: "/Default/TestJson", dataType: "json", type: "post",
success: function (data) {
alert(data.Name);
alert(data.BirthDate);
}, error: function () {
alert('error json');
}
});
});
});
</script>
<div>
<button id="btn1">单击</button>
</div>


4.运行项目,如果测试无误,肯定会依次弹窗显示出Name和BirthDate的信息。
5.上面就是普通的Json传递数据方式。现在改用Json.Net(也就是newtonjs)来传递Json数据。上面代码依然保留,等会儿做部分修改。

二、改用Json.Net(也就是newtonjs)来传递Json数据

1.先用命令给项目安装Jso
4000
n.Net,在程序包管理器控制台中输入命令:

Install-Package newtonsoft.json

给MVC项目安装必要文件。当然还有简单的方式代替这一步操作,直接引用类库文件Newtonsoft.Json.dll也能达到同样效果。文件下载地址:https://www.newtonsoft.com/json

2.新建JsonNetResult.cs类,继承自JsonResult.cs类。实际上转到JsonResult.cs类的定义,可以看到这个类还继承自ActionResult类,所以这里继承自JsonResult类,相当于自定义ActionResult。下面的代码不需要会默写,只要会使用就可以了,详细代码如下:

public class JsonNetResult : JsonResult
{
public JsonNetResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
DateFormatString = "yyyy-MM-dd HH:mm:ss",
ContractResolver = new
Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
};
}

public JsonSerializerSettings Settings { get; private set; }

public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
&& string.Equals(context.HttpContext.Request.HttpMethod, "GET",

StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("JSON GET is not allowed");
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ?

"application/json" : this.ContentType;
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data == null)
{
return;
}
var scriptSerializer = JsonSerializer.Create(this.Settings);
scriptSerializer.Serialize(response.Output, this.Data);
}
}

3.在TestJson.cshtml视图中,将两个属性的首字母改为小写。因为后台处理好的Json格式内容里,属性的首字母都已经转换成了小写,前台因此也要做相应的变更。详细改变的代码如下:
alert(data.name);

alert(data.birthDate);

4.标记有[HttpPost]的TestJson方法,将return Json(Person);修改成return new JsonNetResult() { Data = per };这时候再运行,如果正常的话,会发现不但能输出name的值,还有birthDate的值也转换成了正常的日期格式。

5.【补充】

在JsonNetResult.cs类中,有一个DateFormatString = "yyyy-MM-dd HH:mm:ss",这个字符串里面的格式是要转换成的日期格式,这里的是完整的年月日时分秒,当然自己也可以改成想要的日期格式,比如只要年月日格式,那就是yyyy-MM-dd
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: