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

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

问题描述

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

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

根据我的研究,似乎实现此目的的唯一方法是 扩展 ActionResult 作为 MVC3 中的 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)

EDIT 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);
    }

EDIT 2:我按照以下建议删除了对数据为空的检查.这应该会让较新版本的 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.

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

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