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

As an example consider the following C# class:

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

By default, when returning an instance of this class from an MVC controller as JSON, it'll be serialized in the following fashion:

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

I would like it to be serialized (by JSON.NET) as:

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

How do I do this?

推荐答案

我在Mats Karlsson的blog本书中找到了一个很好的解决这个问题的方案.解决方案是编写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));
    }
}

Then use this class as follows in your MVC controller method:

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

Json相关问答推荐

Jolt转换问题—使用键查找匹配对象

JSON字符串处理注入引号

如何使用GoFr返回XML响应?

如何在VB6中将字符串转换或解码为可读格式?

当列为空时从 SQL 获取 JSON

使用 jq 重新格式化 JSON 输出

如何将属性拆分为嵌套的JSON内容?

如何将一个对象添加到多个对象中 JOLT

使用不同行数的数据创建嵌套Jolt

使用本地 JSON api react TS Axios

无法使用 vue.js 访问 JSON 数组的项目

如何将该 JSON 解析为 Kotlin 类?

UTF-8 字符编码之战 json_encode()

避免 KeyError 的默认字典键

在 Rails 3 中处理 JS/ERB 模板中的 JSON

将 Objective-C 对象序列化和反序列化为 JSON

JSON JQ 如果没有 else

python追加到json对象中的数组

Javascript:如何判断 AJAX 响应是否为 JSON

NSURLRequest 中不支持的 URL