更新
感谢所有答案。我正在开展一个新项目,看起来我终于明白了这一点:看起来下面的代码实际上应该归咎于:
public static HttpResponseMessage GetHttpSuccessResponse(object response, HttpStatusCode code = HttpStatusCode.OK)
{
return new HttpResponseMessage()
{
StatusCode = code,
Content = response != null ? new JsonContent(response) : null
};
}
...别处
public JsonContent(object obj)
{
var encoded = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore } );
_value = JObject.Parse(encoded);
Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
我忽略了看似无害的JsonContent,假设它是WebAPI但没有。
这是到处使用 ...我可以成为第一个说,wtf?或许这应该是"他们为什么要这样做?"
原始问题如下
有人会认为这将是一个简单的配置设置,但现在它已经躲过了我很长时间。
我看过各种解决方案和答案:
https://gist.github.com/rdingwall/2012642
似乎不适用于最新的WebAPI版本......
以下似乎不起作用 - 属性名称仍为PascalCased。
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.UseDataContractJsonSerializer = true;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Mayank的回答:CamelCase JSON WebAPI Sub-Objects (Nested objects, child objects)似乎是一个令人不满意但可行的答案,直到我意识到这些属性必须添加到生成的代码中,因为我们正在使用linq2sql ......
任何方式自动执行此操作?这个讨厌的'我已经困扰了很长一段时间了。
答案 0 :(得分:160)
把它们放在一起你得到......
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
}
答案 1 :(得分:26)
这对我有用:
internal static class ViewHelpers
{
public static JsonSerializerSettings CamelCase
{
get
{
return new JsonSerializerSettings {
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
}
}
}
然后:
[HttpGet]
[Route("api/campaign/list")]
public IHttpActionResult ListExistingCampaigns()
{
var domainResults = _campaignService.ListExistingCampaigns();
return Json(domainResults, ViewHelpers.CamelCase);
}
课程CamelCasePropertyNamesContractResolver
来自Json.NET库中的Newtonsoft.Json.dll
。
答案 2 :(得分:12)
事实证明
return Json(result);
是罪魁祸首,导致序列化过程忽略了camelcase设置。那个
return Request.CreateResponse(HttpStatusCode.OK, result, Request.GetConfiguration());
是我正在寻找的机器人。
另外
json.UseDataContractJsonSerializer = true;
正在使用扳手,原来并不是我正在寻找的机器人。
答案 3 :(得分:12)
以上所有答案对Owin Hosting和Ninject都不起作用。这对我有用:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
// Get the ninject kernel from our IoC.
var kernel = IoC.GetKernel();
var config = new HttpConfiguration();
// More config settings and OWIN middleware goes here.
// Configure camel case json results.
ConfigureCamelCase(config);
// Use ninject middleware.
app.UseNinjectMiddleware(() => kernel);
// Use ninject web api.
app.UseNinjectWebApi(config);
}
/// <summary>
/// Configure all JSON responses to have camel case property names.
/// </summary>
private void ConfigureCamelCase(HttpConfiguration config)
{
var jsonFormatter = config.Formatters.JsonFormatter;
// This next line is not required for it to work, but here for completeness - ignore data contracts.
jsonFormatter.UseDataContractJsonSerializer = false;
var settings = jsonFormatter.SerializerSettings;
#if DEBUG
// Pretty json for developers.
settings.Formatting = Formatting.Indented;
#else
settings.Formatting = Formatting.None;
#endif
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
关键区别在于:新的HttpConfiguration()而不是GlobalConfiguration.Configuration。
答案 4 :(得分:7)
WebApiConfig代码:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//This line sets json serializer's ContractResolver to CamelCasePropertyNamesContractResolver,
// so API will return json using camel case
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
确保您的API Action Method以下列方式返回数据,并且您已安装最新版本的Json.Net/Newtonsoft.Json已安装:
[HttpGet]
public HttpResponseMessage List()
{
try
{
var result = /*write code to fetch your result*/;
return Request.CreateResponse(HttpStatusCode.OK, cruises);
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
答案 5 :(得分:4)
在你的Owin Startup中添加这一行......
public class Startup
{
public void Configuration(IAppBuilder app)
{
var webApiConfiguration = ConfigureWebApi();
app.UseWebApi(webApiConfiguration);
}
private HttpConfiguration ConfigureWebApi()
{
var config = new HttpConfiguration();
// ADD THIS LINE HERE AND DONE
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.MapHttpAttributeRoutes();
return config;
}
}
答案 6 :(得分:3)
这是一个模糊的,当路由属性与GET url不匹配但GET url与方法名称匹配时,jsonserializer camel case指令将被忽略,例如。
//uppercase fail cakes
[HttpGet]
[Route("countries")]
public async Task<GeoData> GeoData()
{
return await geoService.GetGeoData();
}
//lowercase nomnomnom cakes
[HttpGet]
[Route("geodata")]
public async Task<GeoData> GeoData()
{
return await geoService.GetGeoData();
}
答案 7 :(得分:1)
我已经按照方式解决了这个问题。
[AllowAnonymous]
[HttpGet()]
public HttpResponseMessage GetAllItems(int moduleId)
{
HttpConfiguration config = new HttpConfiguration();
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
try
{
List<ItemInfo> itemList = GetItemsFromDatabase(moduleId);
return Request.CreateResponse(HttpStatusCode.OK, itemList, config);
}
catch (System.Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
答案 8 :(得分:0)
我正在使用WebApi和Breeze,当我尝试在微风控制器中执行非微风动作时,我遇到了同样的问题。我尝试使用apprach Request.GetConfiguration但结果相同。因此,当我访问Request.GetConfiguration返回的对象时,我意识到请求使用的序列化程序是breeze-server用来使它变得神奇的一个。无论如何,我解决了我的问题,创建了一个不同的HttpConfiguration:
public static HttpConfiguration BreezeControllerCamelCase
{
get
{
var config = new HttpConfiguration();
var jsonSerializerSettings = config.Formatters.JsonFormatter.SerializerSettings;
jsonSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
return config;
}
}
并将其作为参数传递给Request.CreateResponse,如下所示:
return this.Request.CreateResponse(HttpStatusCode.OK, result, WebApiHelper.BreezeControllerCamelCase);