36

我试图让我的操作返回一个 JsonResult,它的所有属性都在 camelCase 中。

我有一个简单的模型:

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

    public string SomeString { get; set; }
}

还有一个简单的控制器动作:

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 序列化:如何控制属性名称?他们将 DataMember 定义设置为模型的每个属性,但我真的不想这样做。

我还找到了一个链接,他们说可以完全解决这类问题:http ://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-序列化#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来解决这个问题。我试过了,但我无法让它工作。

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

4

2 回答 2

17

如果您想从您的操作中返回一个遵循驼峰表示法的 json 字符串,您必须创建一个 JsonSerializerSettings 实例并将其作为 JsonConvert.SerializeObject(a,b) 方法的第二个参数传递。

public string GetSerializedCourseVms()
    {
        var courses = new[]
        {
            new CourseVm{Number = "CREA101", Name = "Care of Magical Creatures", Instructor ="Rubeus Hagrid"},
            new CourseVm{Number = "DARK502", Name = "Defence against dark arts", Instructor ="Severus Snape"},
            new CourseVm{Number = "TRAN201", Name = "Transfiguration", Instructor ="Minerva McGonal"}
        };
        var camelCaseFormatter = new JsonSerializerSettings();
        camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
        return JsonConvert.SerializeObject(courses, camelCaseFormatter);
    }
于 2014-03-28T05:03:33.840 回答
13

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 控制器函数(如果需要/想要)。您可以创建新的或覆盖现有的,这取决于您。您可能也会对此链接感兴趣。

于 2013-02-26T10:11:12.483 回答