使用 JSON.NET 作为 ASP.NET MVC 3 中的默认 JSON 序列化程序 - 可能吗? [英] Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it possible?

查看:16
本文介绍了使用 JSON.NET 作为 ASP.NET MVC 3 中的默认 JSON 序列化程序 - 可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 JSON.NET 作为 ASP.NET MVC 3 中的默认 JSON 序列化程序?

Is it possible to use JSON.NET as default JSON serializer in ASP.NET MVC 3?

根据我的研究,似乎实现此目的的唯一方法是 扩展 ActionResultMVC3 中的 JsonResult 不是虚拟的...

According to my research, it seems that the only way to accomplish this is to extend ActionResult as JsonResult in MVC3 is not virtual...

我希望通过 ASP.NET MVC 3 可以指定一个可插入的提供程序以序列化为 JSON.

I hoped that with ASP.NET MVC 3 that there would be a way to specify a pluggable provider for serializing to JSON.

想法?

推荐答案

我相信最好的方法是 - 如您的链接中所述 - 扩展 ActionResult 或直接扩展 JsonResult.

I believe the best way to do it, is - as described in your links - to extend ActionResult or extend JsonResult directly.

至于方法JsonResult在控制器上不是虚的那不是真的,选择合适的重载就好了.这很好用:

As for the method JsonResult that is not virtual on the controller that's not true, just choose the right overload. This works well:

protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)

编辑 1:一个 JsonResult 扩展...

EDIT 1: A JsonResult extension...

public class JsonNetResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");

        var response = context.HttpContext.Response;

        response.ContentType = !String.IsNullOrEmpty(ContentType) 
            ? ContentType 
            : "application/json";

        if (ContentEncoding != null)
            response.ContentEncoding = ContentEncoding;

        // If you need special handling, you can call another form of SerializeObject below
        var serializedObject = JsonConvert.SerializeObject(Data, Formatting.Indented);
        response.Write(serializedObject);
    }

编辑 2:根据以下建议,我删除了对 Data 为 null 的检查.这应该使 JQuery 的较新版本感到高兴,并且似乎是明智的做法,因为响应可以被无条件地反序列化.但请注意,这不是来自 ASP.NET MVC 的 JSON 响应的默认行为,而是在没有数据时以空字符串响应.

EDIT 2: I removed the check for Data being null as per the suggestions below. That should make newer versions of JQuery happy and seems like the sane thing to do, as the response can then be unconditionally deserialized. Be aware though, that this is not the default behavior for JSON responses from ASP.NET MVC, which rather responds with an empty string, when there's no data.

这篇关于使用 JSON.NET 作为 ASP.NET MVC 3 中的默认 JSON 序列化程序 - 可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆