一.Newtonsoft.Json仅 依赖.Net Standard所以支持.Net Framework也支持.Net Core
二.使用实例
Jquery 的ajax get请求
1
2
3
4
5
6
7
|
$( '#btnOne' ).click(function () {
//使用ajax get请求json 数据
$. get ( '@Url.Action("DataOne")' , {}, function (data) {
console.info(data);
console.info(data[0].menuName);
});
});
|
1.默认情况,使用驼峰样式处理字段名Key
1
2
3
4
5
6
7
|
public JsonResult DataThree()
{
List<Menu> menus = _context.Menu
.ToList();
return Json(menus);
}
|
2.设置不使用驼峰格式处理,由后台字段确定大小写,也就是默认格式(基本搞定)
1
2
3
4
5
6
7
8
9
10
11
|
public JsonResult DataOne()
{
List<Menu> menus = _context.Menu.ToList();
JsonSerializerSettings settings = new JsonSerializerSettings();
//EF Core中默认为驼峰样式序列化处理key
//settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
//使用默认方式,不更改元数据的key的大小写
settings.ContractResolver = new DefaultContractResolver();
return Json(menus, settings);
}
|
3.处理循环引用,加载关联表数据
1
2
3
4
5
6
7
8
9
10
11
|
public JsonResult DataTwo()
{
List<Menu> menus = _context.Menu
.Include(q => q.Model)
.ToList();
//处理循环引用问题
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MaxDepth = 2;
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //设置不处理循环引用
return Json(menus, settings);
}
|
三、全局设置,Json序列化配置(每次都写设置太麻烦)
在Startup文件中修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc()
//全局配置Json序列化处理
.AddJsonOptions(options =>
{
//忽略循环引用
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//不使用驼峰样式的key
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
//设置时间格式
options.SerializerSettings.DateFormatString = "yyyy-MM-dd" ;
}
);
}
|
|
请发表评论