I am trying to make my action return a JsonResult where all its properties are in camelCase.

我有一个简单的模型:

public class MyModel
{
    public int SomeInteger { get; set; }

    public string SomeString { get; set; }
}

And a simple controller action:

public JsonResult Index()
    {
        MyModel model = new MyModel();
        model.SomeInteger = 1;
        model.SomeString = "SomeString";

        return Json(model, JsonRequestBehavior.AllowGet);
    }

Calling this action method now returns a JsonResult containing the following data:

{"SomeInteger":1,"SomeString":"SomeString"}

出于我的使用目的,我需要在camelCase中返回数据,某种程度上如下所示:

{"someInteger":1,"someString":"SomeString"}

有什么优雅的方法可以做到这一点吗?

我在这里寻找可能的解决方案,找到了MVC3 JSON Serialization: How to control the property names?个,他们在其中为模型的每个属性设置DataMember定义,但我真的不想这么做.

我还找到了一个链接,他们说完全有可能解决这类问题:http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_camelcasing.上面写着:

To write JSON property names with camel casing, without changing your data model, set the CamelCasePropertyNamesContractResolver on the serializer:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

这个博客http://frankapi.wordpress.com/2012/09/09/going-camelcase-in-asp-net-mvc-web-api/上的一个条目也提到了这个解决方案,并表示你可以简单地将它添加到RouteConfig.RegisterRoutes中来解决这个问题.我试过了,但没能成功.

你们知道我哪里做错了什么吗?

推荐答案

控制器的Json函数只是用于创建JsonResults的包装器:

protected internal JsonResult Json(object data)
{
    return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
}

protected internal JsonResult Json(object data, string contentType)
{
    return Json(data, contentType, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
}

protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding)
{
    return Json(data, contentType, contentEncoding, JsonRequestBehavior.DenyGet);
}

protected internal JsonResult Json(object data, JsonRequestBehavior behavior)
{
    return Json(data, null /* contentType */, null /* contentEncoding */, behavior);
}

protected internal JsonResult Json(object data, string contentType, JsonRequestBehavior behavior)
{
    return Json(data, contentType, null /* contentEncoding */, behavior);
}

protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
    return new JsonResult
    {
        Data = data,
        ContentType = contentType,
        ContentEncoding = contentEncoding,
        JsonRequestBehavior = behavior
    };
}

JsonResult internally uses JavaScriptSerializer, so you don't have control about the serialisation process:

public class JsonResult : ActionResult
{
    public JsonResult()
    {
        JsonRequestBehavior = JsonRequestBehavior.DenyGet;
    }

    public Encoding ContentEncoding { get; set; }

    public string ContentType { get; set; }

    public object Data { get; set; }

    public JsonRequestBehavior JsonRequestBehavior { get; set; }

    /// <summary>
    /// When set MaxJsonLength passed to the JavaScriptSerializer.
    /// </summary>
    public int? MaxJsonLength { get; set; }

    /// <summary>
    /// When set RecursionLimit passed to the JavaScriptSerializer.
    /// </summary>
    public int? RecursionLimit { 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(MvcResources.JsonRequest_GetNotAllowed);
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            if (MaxJsonLength.HasValue)
            {
                serializer.MaxJsonLength = MaxJsonLength.Value;
            }
            if (RecursionLimit.HasValue)
            {
                serializer.RecursionLimit = RecursionLimit.Value;
            }
            response.Write(serializer.Serialize(Data));
        }
    }
}

您必须创建自己的JsonResult并编写自己的Json控制器函数(如果需要).你可以创建新的或覆盖现有的,这取决于你.这link个可能也会让你感兴趣.

Json相关问答推荐

在Go中,当字段可以根据其他字段具有不同的类型时,什么是正确的方法来卸载JSON?

Google Page to JSON应用程序脚本出现CORS错误

替换字符串中特殊字符的Jolt变换

在Zig中解析JSON失败

如何在JSONata对象中迭代并向数组添加新字段?

对一些JSON模式验证的混淆

将boost::beast::multibuffer转换为std::istream

在Databricks中如何将JSON文件作为字典读取

Jolt 不打印任何东西

jq :当路径可变时更新 json 内容

jq :遍历 json 并在键存在时检索集合

将请求中的数据推送到数组中

我需要在 mongodb compass 中检索索引(编号 1)信息

使用 jq 获取特定键的所有父键

使用 JQ 从文件中删除重复的 JSON 块

Jackson 中的 readValue 和 readTree:何时使用哪个?

alert Json 对象

我应该如何处理 JSON 中的 HATEOAS 链接和引用?

如何将单引号转义成双引号转成单引号

ASP.NET Web API JSON 输出中没有时间的日期