This question already has answers here:
Proper JSON serialization in MVC 4

(4个答案)


4年前关闭。




我试图使我的 Action 返回一个JsonResult,其所有属性都在camelCase中。

我有一个简单的模型:
public class MyModel
{
    public int SomeInteger { get; set; }

    public string SomeString { get; set; }
}

和一个简单的 Controller Action :
public JsonResult Index()
    {
        MyModel model = new MyModel();
        model.SomeInteger = 1;
        model.SomeString = "SomeString";

        return Json(model, JsonRequestBehavior.AllowGet);
    }

现在,调用此操作方法将返回包含以下数据的JsonResult:
{"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。它说:

要使用驼峰式写法写JSON属性名称而不更改数据模型,请在序列化程序上设置CamelCasePropertyNamesContractResolver:
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 中即可解决此问题。我尝试过,但是无法正常工作。

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

最佳答案

Controller的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内部使用JavaScriptSerializer,因此您无法控制序列化过程:
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 Controller函数(如果需要/需要)。您可以创建新的或覆盖现有的,由您决定。这个link可能也会使您感兴趣。

关于asp.net-mvc - MVC JsonResult camelCase序列化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15040838/

10-12 06:51