如何在ASP.NET MVC控制器方法中使用JSON.NET返回camelCase JSON序列化?

22 浏览
0 Comments

如何在ASP.NET MVC控制器方法中使用JSON.NET返回camelCase JSON序列化?

我的问题是我希望通过ActionResult在ASP.NET MVC控制器方法中返回驼峰式(而不是标准的帕斯卡式)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"
}

我该怎么做?

admin 更改状态以发布 2023年5月24日
0
0 Comments

我在Mats Karlsson的博客上找到了一个极好的解决方案来解决这个问题。该解决方案是编写一个ActionResult的子类,通过JSON.NET序列化数据,配置后者遵循驼峰命名约定:

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

0
0 Comments

或者,简而言之:

JsonConvert.SerializeObject(
    , 
    new JsonSerializerSettings 
    { 
        ContractResolver = new CamelCasePropertyNamesContractResolver() 
    });

例如:

return new ContentResult
{
    ContentType = "application/json",
    Content = JsonConvert.SerializeObject(new { content = result, rows = dto }, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }),
    ContentEncoding = Encoding.UTF8
};

0