小编典典

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

json

我的问题是,我希望通过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"
}

我该怎么做呢?


阅读 217

收藏
2020-07-27

共1个答案

小编典典

我在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)};
}
2020-07-27