小编典典

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

all

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

例如,考虑以下 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"
}

我该怎么做呢?


阅读 70

收藏
2022-04-26

共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)};
}
2022-04-26