gpt4 book ai didi

c# - 对象及其子对象上的 Web API 2 : how to return JSON with camelCased property names,

转载 作者:IT王子 更新时间:2023-10-29 03:36:42 25 4
gpt4 key购买 nike

更新

谢谢大家的回答。我在一个新项目上,看起来我终于弄清楚了这个问题:看起来实际上应该归咎于以下代码:

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...

有什么方法可以自动执行此操作?这个“讨厌”已经困扰了我很长时间了。

最佳答案

把它们放在一起你会得到...

protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
}

关于c# - 对象及其子对象上的 Web API 2 : how to return JSON with camelCased property names,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28552567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com