每个Web API请求设置JSON驼峰 [英] Set JSON CamelCase per Web API request

查看:739
本文介绍了每个Web API请求设置JSON驼峰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

网络API使用Json.Net格式化程序序列化的JSON响应,让你在启动时使用非常方便地自定义生成的JSON格式为整个应用程序:

Web API uses the Json.Net formatter to serialise its JSON responses which allows you to customise the format of the generated JSON very easily for the entire application at startup using:

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

这允许你解决C#语法preferring PascalCase和基于JavaScript的客户preferring驼峰之间的问题。但是在API不考虑谁的客户端请求实际上是从全球范围来设置这似乎假设一个API将只有1个类型的客户,无论您为您的API集仅仅是它必须的方式。

This allows you resolve the issues between C# syntax preferring PascalCase and javascript based clients preferring camelCase. However setting this globally on the API without taking into consideration who the client request is actually coming from seems to assume that an API will only have 1 type of client and whatever you set for your API is just the way it has to be.

通过多种客户端我的API(JavaScript的,iOS版,Android版,C#),我正在寻找一种方法来设置Json.Net SerializerSettings 每个请求,这样客户端可以请求其$ p $通过一些手段(也许是自定义标题和查询字符串参数),以覆盖默认值。pferred格式

With multiple client types for my API's (javascript, iOS, Android, C#), I'm looking for a way to set the Json.Net SerializerSettings per request such that the client can request their preferred format by some means (perhaps a custom header or queryString param) to override the default.

什么是设置在网页API每个请求Json.Net SerializerSettings的最佳方式?

What would be the best way to set per-request Json.Net SerializerSettings in Web API?

推荐答案

从里克施特拉尔的的博客文章,我想出了一个解决方案,允许动态切换API从驼峰到PascalCase基于客户端的请求。

With a bit of help from Rick Strahl's blog post on creating a JSONP media type formatter, I have come up with a solution that allows the API to dynamically switch from camelCase to PascalCase based on the client request.

创建一个从默认JsonMediaTypeFormatter派生并重写GetPerRequestFormatterInstance方法MediaTypeFormatter。在这里,你可以实现你的逻辑基础上,要求设置你的串行设置。

Create a MediaTypeFormatter that derives from the default JsonMediaTypeFormatter and overrides the GetPerRequestFormatterInstance method. This is where you can implement your logic to set your serializer settings based on the request.

public class JsonPropertyCaseFormatter : JsonMediaTypeFormatter
{
    private readonly JsonSerializerSettings globalSerializerSettings;

    public JsonPropertyCaseFormatter(JsonSerializerSettings globalSerializerSettings)
    {
        this.globalSerializerSettings = globalSerializerSettings;
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));
    }

    public override MediaTypeFormatter GetPerRequestFormatterInstance(
        Type type,
        HttpRequestMessage request,
        MediaTypeHeaderValue mediaType)
    {
        var formatter = new JsonMediaTypeFormatter
        {
            SerializerSettings = globalSerializerSettings
        };

        IEnumerable<string> values;

        var result = request.Headers.TryGetValues("X-JsonResponseCase", out values)
            ? values.First()
            : "Pascal";

        formatter.SerializerSettings.ContractResolver = 
            result.Equals("Camel", StringComparison.InvariantCultureIgnoreCase)
                ? new CamelCasePropertyNamesContractResolver()
                : new DefaultContractResolver();

        return formatter;
    }
}

请注意,我采取了JsonSerializerSettings参数作为一个构造函数参数,这样我们就可以继续使用WebApiConfig设置任何其他JSON的设置,我们要使用,让他们在这里仍然适用。

Note that I take a JsonSerializerSettings argument as a constructor param so that we can continue to use WebApiConfig to set up whatever other json settings we want to use and have them still applied here.

要注册那么此格式,在你WebApiConfig:

To then register this formatter, in your WebApiConfig:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;

config.Formatters.Insert(0,
    new JsonPropertyCaseFormatter(config.Formatters.JsonFormatter.SerializerSettings));

现在有的头值要求的X JsonResponseCase:骆驼将在响应中接收驼峰属性名称。很明显,你可以改变这种逻辑来使用任何你喜欢的页眉或查询字符串参数。

Now requests that have a header value of X-JsonResponseCase: Camel will receive camel case property names in the response. Obviously you could change that logic to use any header or query string param you like.

这篇关于每个Web API请求设置JSON驼峰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆