问题描述
更新
感谢所有的答案。我是一个新的项目,它看起来像我终于得到了这条底线:它看起来像下面的code实际上要怪:
Thanks for all the answers. I am on a new project and it looks like I've finally got to the bottom of this: It looks like the following code was in fact to blame:
public static HttpResponseMessage GetHttpSuccessResponse(object response, HttpStatusCode code = HttpStatusCode.OK)
{
return new HttpResponseMessage()
{
StatusCode = code,
Content = response != null ? new JsonContent(response) : null
};
}
在其他地方...
elsewhere...
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,但没有。
I had overlooked the innocuous looking JsonContent assuming it was WebAPI but no.
这是使用的处处的......可我只是第一个说,跆拳道?或许这应该是他们为什么要这样做?
This is used everywhere... Can I just be the first to say, wtf? Or perhaps that should be "Why are they doing this?"
原题如下的
人们会以为这是一个简单的配置设置,但它躲避我太久了。
One would have thought this would be a simple config setting, but it's eluded me for too long now.
我已经看过了各种解决方案和答案:
I have looked at various solutions and answers:
https://gist.github.com/rdingwall/2012642
似乎并不适用于最新的WebAPI的版本...
doesn't seem to apply to latest WebAPI version...
下面似乎并没有工作 - 属性名称仍PascalCased
The following doesn't seem to work - property names are still 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子对象(嵌套对象,子对象)似乎是不令人满意的,但可行的答案,直到我意识到这些属性将不得不为我们使用的是被添加到产生code LINQ2SQL ...
Mayank's answer here: CamelCase JSON WebAPI Sub-Objects (Nested objects, child objects) seemed like an unsatisfactory but workable answer until I realised these attributes would have to be added to generated code as we are using linq2sql...
任何方式自动做到这一点?这种讨厌一直困扰了我很长一段时间了。
Any way to do this automatically? This 'nasty' has plagued me for a long time now.
推荐答案
全部放在一起你...
Putting it all together you get...
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
}
这篇关于网络API 2:如何返回JSON与驼峰格式属性名称,在对象及其子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!