使用JSON.Net的Web API出现驼峰问题 [英] Camel-Casing Issue with Web API Using JSON.Net

查看:43
本文介绍了使用JSON.Net的Web API出现驼峰问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Web API返回驼峰式JSON数据.我继承了一个项目的混乱局面,该项目使用了以前的程序员目前想使用的任何大小写形式(严重!所有大写字母,小写字母,pascal-casing和ampel-casing-随便选择!),所以我不能使用将其放入WebApiConfig.cs文件的技巧,因为它会破坏现有的API调用:

I would like to return camel-cased JSON data using Web API. I inherited a mess of a project that uses whatever casing the previous programmer felt like using at the moment (seriously! all caps, lowercase, pascal-casing & camel-casing - take your pick!), so I can't use the trick of putting this in the WebApiConfig.cs file because it will break the existing API calls:

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

因此,我正在使用使用JSON.Net序列化程序的自定义类.这是代码:

So I'm using a custom class that uses the JSON.Net serializer. Here is the code:

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;
    }
}

问题在于返回的原始数据如下:

The problem is that the raw data returned looks like this:

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

如您所见,反斜杠使事情变得混乱.这是我使用自定义类进行调用的方式:

As you can see, the backslashes mess things up. Here is how I'm calling using the custom class:

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);

}

我可以采取哪些其他措施来消除反斜杠?有没有其他方法来执行骆驼保护套?

What can I do differently to get rid of the backslashes? Is there an alternative way to enforcing camel-casing?

推荐答案

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

Thanks to all the references to other Stackoverflow pages, I'm going to post three solutions so anyone else having a similar issue can take their pick of the code. The first code example is one that I created after looking at what other people were doing. The last two are from other Stackoverflow users. I hope this helps someone else!

// 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控制器方法.

The second solution uses an attribute to decorate the API controller method.

// 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控制器.

The last solution uses an attribute to decorate the entire API controller.

// 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
{
    ...
}

这篇关于使用JSON.Net的Web API出现驼峰问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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