问题描述
当我的json从服务器返回时,它在CamelCase中,但是我需要小写。我已经看到了很多针对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);
}
我希望“名称”为小写。
解决方法
为此,我最好的解决方案是重写默认的Json
方法以使用Newtonsoft.Json
并将其默认设置为使用驼峰式。
第一件事是,如果您还没有基本控制器,则需要制作一个基本控制器,并使您的控制器继承该基本控制器。
public class BaseController : Controller {
}
接下来,您将创建一个将使用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));
}
}
然后在您的BaseController
中覆盖Json
方法:
protected new JsonResult Json(object data)
{
return new JsonCamelcaseResult
{
Data = data,JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
因此,在返回JSON的原始操作中,最后只需保持相同即可,并且属性将使用驼峰式(propertyName)而不是pascalcased(PropertyName):
[HttpGet]
public JsonResult Method()
{
var vms = new List<MyViewModel>()
{
new MyViewModel()
{
Name = "John Smith",}
};
return Json(new { results = vms });
}