【问题标题】:Camel-Casing Issue with Web API Using JSON.Net使用 JSON.Net 的 Web API 的骆驼大小写问题
【发布时间】:2014-06-23 16:07:02
【问题描述】:

我想使用 Web API 返回骆驼大小写的 JSON 数据。我继承了一个乱七八糟的项目,它使用了前任程序员目前喜欢使用的任何外壳(说真的!所有大写字母、小写字母、pascal-casing 和 camel-casing - 随你选!),所以我不能使用这个技巧把它放在 WebApiConfig.cs 文件中,因为它会破坏现有的 API 调用:

// Enforce camel-casing for the JSON objects being returned from API calls.
config.Formatters.OfType<JsonMediaTypeFormatter>().First().SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

所以我使用了一个使用 JSON.Net 序列化程序的自定义类。代码如下:

using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

public class JsonNetApiController : ApiController
{
    public string SerializeToJson(object objectToSerialize)
    {
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };

        if (objectToSerialize != null)
        {
            return JsonConvert.SerializeObject(objectToSerialize, Formatting.None, settings);
        }

        return string.Empty;
    }
}

问题是返回的原始数据是这样的:

"[{\"average\":54,\"group\":\"P\",\"id\":1,\"name\":\"Accounting\"}]"

如您所见,反斜杠把事情搞砸了。这是我使用自定义类调用的方式:

public class Test
{
    public double Average { get; set; }
    public string Group { get; set; }
    public int Id { get; set; }
    public string Name { get; set; }
}

public class SomeController : JsonNetApiController
{
    public HttpResponseMessage Get()

    var responseMessage = new List<Test>
    {
        new Test
        {
            Id = 1,
            Name = "Accounting",
            Average = 54,
            Group = "P",
        }
    };

    return Request.CreateResponse(HttpStatusCode.OK, SerializeToJson(responseMessage), JsonMediaTypeFormatter.DefaultMediaType);

}

我可以做些什么来摆脱反斜杠?是否有其他方法可以强制执行骆驼套管?

【问题讨论】:

  • 您是否希望在不影响全局 json 格式化程序设置的情况下为每个控制器设置骆驼外壳?如果是,那么有一种方法可以在 Web API 中做到这一点
  • @Halcyon:您可以将问题的“答案”部分作为答案发布吗?
  • @StriplingWarrior 完成。

标签: c# html json asp.net-mvc asp.net-web-api


【解决方案1】:

感谢所有对其他 Stackoverflow 页面的引用,我将发布三个解决方案,以便其他有类似问题的人可以选择代码。第一个代码示例是我在查看其他人在做什么之后创建的。最后两个来自其他 Stackoverflow 用户。我希望这对其他人有帮助!

// Solution #1 - This is my solution. It updates the JsonMediaTypeFormatter whenever a response is sent to the API call.
// If you ever need to keep the controller methods untouched, this could be a solution for you.
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;
using Newtonsoft.Json.Serialization;

public class CamelCasedApiController : ApiController
{
    public HttpResponseMessage CreateResponse(object responseMessageContent)
    {
        try
        {
            var httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, responseMessageContent, JsonMediaTypeFormatter.DefaultMediaType);
            var objectContent = httpResponseMessage.Content as ObjectContent;

            if (objectContent != null)
            {
                var jsonMediaTypeFormatter = new JsonMediaTypeFormatter
                {
                    SerializerSettings =
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    }
                };

                httpResponseMessage.Content = new ObjectContent(objectContent.ObjectType, objectContent.Value, jsonMediaTypeFormatter);
            }

            return httpResponseMessage;
        }
        catch (Exception exception)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, exception.Message);
        }
    }
}

第二种解决方案使用属性来装饰 API 控制器方法。

// http://stackoverflow.com/questions/14528779/use-camel-case-serialization-only-for-specific-actions
// This code allows the controller method to be decorated to use camel-casing. If you can modify the controller methods, use this approach.
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http.Filters;
using Newtonsoft.Json.Serialization;

public class CamelCasedApiMethodAttribute : ActionFilterAttribute
{
    private static JsonMediaTypeFormatter _camelCasingFormatter = new JsonMediaTypeFormatter();

    static CamelCasedApiMethodAttribute()
    {
        _camelCasingFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }

    public override void OnActionExecuted(HttpActionExecutedContext httpActionExecutedContext)
    {
        var objectContent = httpActionExecutedContext.Response.Content as ObjectContent;
        if (objectContent != null)
        {
            if (objectContent.Formatter is JsonMediaTypeFormatter)
            {
                httpActionExecutedContext.Response.Content = new ObjectContent(objectContent.ObjectType, objectContent.Value, _camelCasingFormatter);
            }
        }
    }
}

// Here is an example of how to use it.
[CamelCasedApiMethod]
public HttpResponseMessage Get()
{
    ...
}

最后一种解决方案是使用一个属性来装饰整个 API 控制器。

// http://stackoverflow.com/questions/19956838/force-camalcase-on-asp-net-webapi-per-controller
// This code allows the entire controller to be decorated to use camel-casing. If you can modify the entire controller, use this approach.
using System;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http.Controllers;
using Newtonsoft.Json.Serialization;

public class CamelCasedApiControllerAttribute : Attribute, IControllerConfiguration
{
    public void Initialize(HttpControllerSettings httpControllerSettings, HttpControllerDescriptor httpControllerDescriptor)
    {
        var jsonMediaTypeFormatter = httpControllerSettings.Formatters.OfType<JsonMediaTypeFormatter>().Single();
        httpControllerSettings.Formatters.Remove(jsonMediaTypeFormatter);

        jsonMediaTypeFormatter = new JsonMediaTypeFormatter
        {
            SerializerSettings =
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }
        };

        httpControllerSettings.Formatters.Add(jsonMediaTypeFormatter);
    }
}

// Here is an example of how to use it.
[CamelCasedApiController]
public class SomeController : ApiController
{
    ...
}

【讨论】:

  • 我建议做一个小调整。我相信如果没有发送接受类型,列表中的第一个格式化程序将成为默认格式,因此这种方法可以将您的默认值切换为 xml,这是我在使用 REST 测试工具测试我的 api 时发现的。将 httpControllerSettings.Formatters.Add 行更改为 Insert 索引为 0 使其保持在列表的首位。
  • @TedElliott 这可能是因为您没有传递Accept-Type 标头(值为application/json)。我必须对其进行测试,但我很确定 WebAPI 会返回您请求的类型,如果您不指定,它将使用列表中的第一个。
  • CamelCasedApiControllerAttribute 对我不起作用。但我使用了 CamelCasedApiMethodAttribute 并将其应用于控制器,它适用于所有操作。
【解决方案2】:

如果你想全局设置它,你可以从 HttpConfiguration 中删除当前的 Json 格式化程序,并用你自己的替换它。

public static void Register(HttpConfiguration config)
{
    config.Formatters.Remove(config.Formatters.JsonFormatter);

    var serializer = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
    var formatter = new JsonMediaTypeFormatter { Indent = true, SerializerSettings =  serializer };
    config.Formatters.Add(formatter);
}

【讨论】:

  • 现有的 API 端点在生产中被移动设备使用,因此我无法使用全局解决方案。我必须为新端点找到解决方法。
【解决方案3】:

评论https://stackoverflow.com/a/26506573/887092适用于某些情况,但不适用于其他情况

var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

这种方式适用于其他情况

var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();

因此,使用以下内容覆盖所有基础:

    private void ConfigureWebApi(HttpConfiguration config)
    {
        //..

        foreach (var jsonFormatter in config.Formatters.OfType<JsonMediaTypeFormatter>())
        {
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }

        var singlejsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        singlejsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

    }

【讨论】:

    猜你喜欢
    • 2013-07-16
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多