MVC JsonResult驼峰系列化[复制](MVC JsonResult camelCase s

2019-07-20 09:41发布

这个问题已经在这里有一个答案:

  • 正确的JSON序列在MVC 4 3个回答

我试图让我的动作返回一个JsonResult它全部的性能在驼峰。

我有一个简单的模型:

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"}

对于我的应用我需要的行动返回驼峰的数据,在某种程度上是这样的:

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

是否有任何优雅的方式来做到这一点?

我一直在寻找到可能的解决方案在这里,发现MVC3 JSON序列:如何控制房地产的名字呢? 在那里设置数据成员定义到模型的每一个属性,但我真的不希望这样做。

此外,我发现,他们说,这是可能的解决正是这种问题的链接: 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/也mentiones该解决方案,并指出,你可以简单地把它添加到RouteConfig.RegisterRoutes来解决这个问题。 我试过,但我不能使它工作。

难道你们有我在那里做错了任何想法?

Answer 1:

控制器的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控制器的功能(如果你需要/想这一点)。 您可以创建新的或改写现有的,它是由你。 这种链接也可能会感兴趣。



Answer 2:

如果你想从你的行动将附着于驼峰表示法你必须做什么返回一个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);
    }


文章来源: MVC JsonResult camelCase serialization [duplicate]