MVC JsonResult camelCase序列化

时间:2013-02-23 13:03:46

标签: asp.net-mvc json serialization camelcasing

我试图让我的动作返回一个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 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 即可解决此问题。我试过了,但我无法使它发挥作用。

你们有什么想法我做错了什么吗?

2 个答案:

答案 0 :(得分:15)

如果你想从你的动作中返回一个遵循camelcase表示法的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);
    }

答案 1 :(得分: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 Controller函数(如果你需要/想要的话)。您可以创建新的或覆盖现有的,这取决于您。这个link也可能会让您感兴趣。