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

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

问题描述

是否有可能使用 JSON.NET 在ASP.NET&NBSP默认JSON序列化; MVC  3

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

根据我的研究,似乎只有这样,才能做到这一点是的扩展的ActionResult 的为<一个href=\"http://stackoverflow.com/questions/6883204/change-default-json-serializer-used-in-asp-mvc3\">JsonResult在MVC3不是虚拟 ...

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&NBSP;&MVC NBSP; 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 :我删除了检查数据是否存在空值按下面的建议。这应该使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天全站免登陆