[英]Lowercase Json result in ASP.NET MVC 5
When my json gets returned from the server, it is in CamelCase, but I need lowercase.当我的 json 从服务器返回时,它是 CamelCase,但我需要小写。 I have seen a lot of solutions for ASP.NET Web API and Core, but nothing for ASP.NET MVC 5.我已经看到了很多针对 ASP.NET Web API 和 Core 的解决方案,但对于 ASP.NET MVC 5 却没有。
[HttpGet]
public JsonResult Method()
{
var vms = new List<MyViewModel>()
{
new MyViewModel()
{
Name = "John Smith",
}
};
return Json(new { results = vms }, JsonRequestBehavior.AllowGet);
}
I want "Names" to be lowercase.我希望“名称”为小写。
The best solution I have for this is to override the default Json
method to use Newtonsoft.Json
and set it to use camelcase by default.我对此的最佳解决方案是覆盖默认的Json
方法以使用Newtonsoft.Json
并将其设置为默认使用驼峰式大小写。
First thing is you need to make a base controller if you don't have one already and make your controllers inherit that.第一件事是,如果您还没有一个基本控制器,则需要创建一个基本控制器,并使您的控制器继承它。
public class BaseController : Controller {
}
Next you create a JsonResult
class that will use Newtonsoft.Json :接下来创建一个将使用 Newtonsoft.Json 的JsonResult
类:
public class JsonCamelcaseResult : JsonResult
{
private static readonly JsonSerializerSettings _settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter> { new StringEnumConverter() }
};
public override void ExecuteResult(ControllerContext context)
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !String.IsNullOrEmpty(this.ContentType) ? this.ContentType : "application/json";
response.ContentEncoding = this.ContentEncoding ?? response.ContentEncoding;
if (this.Data == null)
return;
response.Write(JsonConvert.SerializeObject(this.Data, _settings));
}
}
Then in your BaseController
you override the Json
method :然后在您的BaseController
覆盖Json
方法:
protected new JsonResult Json(object data)
{
return new JsonCamelcaseResult
{
Data = data,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
So in the end in your original action returning JSON you just keep it the same and the properties will be camelcased (propertyName) instead of pascalcased (PropertyName) :因此,最终在您返回 JSON 的原始操作中,您只需保持不变,属性将被驼峰式 (propertyName) 而不是 pascalcased (PropertyName) :
[HttpGet]
public JsonResult Method()
{
var vms = new List<MyViewModel>()
{
new MyViewModel()
{
Name = "John Smith",
}
};
return Json(new { results = vms });
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.