本文摘自PHP中文网,作者零下一度,侵删。
1..Net开源Json序列化工具Newtonsoft.Json中提供了解决序列化的循环引用问题:
方式1:指定Json序列化配置为 ReferenceLoopHandling.Ignore
方式2:指定 JsonIgnore忽略 引用对象
实例1,解决MVC的Json序列化引用方法:
step1:在项目上添加引用 Newtonsoft.Json程序包,命令:Insert-Package Newtonsoft.Json
step2:在项目中添加一个类,继承JsonResult,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
public
JsonSerializerSettings Settings { get;
private
set; }
public
JsonNetResult()
{
Settings =
new
JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
}
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);using (
var
sw =
new
StringWriter())
{
scriptSerializer.Serialize(sw, this.Data);
response.Write(sw.ToString());
}
}
}
step3:在项目添加BaseController,重写Json()方法,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
public
class
BaseController : Controller
{
public
StudentContext _Context =
new
StudentContext();
Encoding contentEncoding, JsonRequestBehavior behavior)
{
return
new
JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
}
step4.向平时一样使用就可以了
1
2
3
4
{
List<student> list = _Context.students.Where(q => q.sno ==
"103"
).ToList();
}
获取的结果,说明,这种方式指定忽略循环引用,是在指定循环级数后忽略,返回的json数据中还是有部分循环的数据
解决EF Json序列化循环引用方法2,在指定的关联对象上,添加JsonIgnore 方法注释
1
[JsonIgnore]
public
virtual ICollection<score> scores { get; set; }
返回结果中,没有关联表数据
文章转载自:
以上就是ASP.NET MVC 遇到JSON循环调用的问题应该怎么解决? 的详细内容!
相关阅读 >>
asp.net实现群发邮件功能实例教程
全开源asp.net工作流平台的详细介绍
asp.net动态输出404 http状态代码
asp.net mvc如何正确运用异步编程技术
利用razor引擎生成静态页(asp.net mvc)实例详解
mvc中获得controller、url及action的asp.net方法详解
分享一个“网红脸“”框架实例教程
asp.net mvc 中关于路径这个问题
asp.net(一)基础三层框架项目:web服务器、业务服务器、数据库服务器
在asp.net中所有的自定义用户控件都必须继承什么?
更多相关阅读请进入《javascript 》频道 >>
¥125.8元 清华大学出版社
作者:[美]克里斯琴·内格尔(Christian Nagel)著。出版时间:2019年3月。
转载请注明出处:木庄网络博客 » ASP.NET MVC 遇到JSON循环调用的问题应该怎么解决?