Asp.Net Core中使用Newtonsoft.Json进行序列化处理解决返回值首字母小写
2017-11-20 16:43
2261 查看
一.Newtonsoft.Json仅 依赖.Net Standard所以支持.Net Framework也支持.Net Core
二.使用实例
Jquery 的ajax get请求
1.默认情况,使用驼峰样式处理字段名Key
2.设置不使用驼峰格式处理,由后台字段确定大小写,也就是默认格式(基本搞定)
3.处理循环引用,加载关联表数据
三、全局设置,Json序列化配置(每次都写设置太麻烦)
在Startup文件中修改
大功告成。
原作者:https://www.cnblogs.com/tianma3798/p/6918548.html
二.使用实例
Jquery 的ajax get请求
$('#btnOne').click(function () { //使用ajax get请求json 数据 $.get('@Url.Action("DataOne")', {}, function (data) { console.info(data); console.info(data[0].menuName); }); });
1.默认情况,使用驼峰样式处理字段名Key
public JsonResult DataThree() { List<Menu> menus = _context.Menu .ToList(); return Json(menus); }
2.设置不使用驼峰格式处理,由后台字段确定大小写,也就是默认格式(基本搞定)
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.处理循环引用,加载关联表数据
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文件中修改
// 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"; } ); }
大功告成。
原作者:https://www.cnblogs.com/tianma3798/p/6918548.html
相关文章推荐
- C#使用NewtonSoft进行Json序列化,设置字段首字母小写方法
- 使用Newtonsoft.json 解决 Asp.Net MVC DateTime类型数据Json格式化问题
- ASP.net MVC使用Jquery-pager和Newtonsoft.Json进行分页
- 对于ASP.NET Core 2.0 返回 JsonResult 取消默认json字符第一个字母小写设置
- Asp.Net Core中Json序列化处理整理
- asp.net core视图中使用Json序列化模型
- Asp.net C# 使用Newtonsoft.Json 进行通信
- ASP.NET:使用Newtonsoft.Json序列化和反序列化JSON对象的例子
- Asp.Net中使用Ext和Newtonsoft.Json进行Ajax异步
- ASP.NET:使用Newtonsoft.Json序列化和反序列化JSON对象的例子
- 使用JSON.Net(Newtonsoft.Json)作为ASP.Net MVC的json序列化和反序列化工具
- Asp.Net Core Mvc上Json序列化首字母大小写的问题
- IIS ASP.net使用 Newtonsoft.Json插件 未能加载文件或程序集“Newtonsoft.Json”或它的某一个依赖项解决方法。
- ASP.net MVC使用Jquery-pager和Newtonsoft.Json进行分页
- Asp.net MVC 3 Razor 视图引擎 中使用@输出的内容都会被自动进行HTML编码 问题的解决办法
- ASP.NET一般处理程序新建一个方法里使用context.Response.Write的解决方法
- ASP.NET中JSON如何对时间进行序列化和反序列化
- 解决“使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错”的问题
- 在ASP.NET中使用IHttpHandler处理请求(如自实现AJAX)时,无法获得Session(或者说是Session 为 null)的原因及解决方法
- 使用ASP.NET一般处理程序或WebService返回JSON的实现代码