温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?
asp.net-mvc json json.net camelcasing

其他 - 如何从ASP.NET MVC控制器方法返回由JSON.NET序列化的camelCase JSON?

发布于 2020-04-05 23:49:17

我的问题是,我希望通过ASP.NET MVC控制器方法(由JSON.NET序列化)通过ActionResult来返回camelCased(与标准PascalCase相反)JSON数据

作为示例,请考虑以下C#类:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

默认情况下,当从MVC控制器以JSON返回此类的实例时,它将以以下方式序列化:

{
  "FirstName": "Joe",
  "LastName": "Public"
}

我希望将其序列化(通过JSON.NET)为:

{
  "firstName": "Joe",
  "lastName": "Public"
}

我该怎么做呢?

查看更多

提问者
aknuds1
被浏览
110
aknuds1 2013-10-18 18:58

我在Mats Karlsson的博客中找到了解决此问题的绝佳方法解决方案是编写ActionResult的子类,该子类通过JSON.NET序列化数据,并将后者配置为遵循camelCase约定:

public class JsonCamelCaseResult : ActionResult
{
    public JsonCamelCaseResult(object data, JsonRequestBehavior jsonRequestBehavior)
    {
        Data = data;
        JsonRequestBehavior = jsonRequestBehavior;
    }

    public Encoding ContentEncoding { get; set; }

    public string ContentType { get; set; }

    public object Data { get; set; }

    public JsonRequestBehavior JsonRequestBehavior { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
        }

        var response = context.HttpContext.Response;

        response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data == null)
            return;

        var jsonSerializerSettings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
        response.Write(JsonConvert.SerializeObject(Data, jsonSerializerSettings));
    }
}

然后在MVC控制器方法中按如下所示使用此类:

public ActionResult GetPerson()
{
    return new JsonCamelCaseResult(new Person { FirstName = "Joe", LastName = "Public" }, JsonRequestBehavior.AllowGet)};
}