返回转义的Json在MVC与Json.Net [英] Returning unescaped Json in MVC with Json.Net

查看:156
本文介绍了返回转义的Json在MVC与Json.Net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有令人惊讶的麻烦试图找出如何返回转义JSON,在MVC项目中使用Json.Net。它是完全影射我,但我敢肯定,我失去了一些东西简单...

I'm having surprising trouble trying to figure out how to return unescaped Json, using Json.Net in an MVC project. It's completely alluding me, but I'm sure I'm missing something simple...

到目前为止,我序列化一个基本的对象,并得到Json.Net序列化的:

So far, I serialize a basic object, and get Json.Net to serialize it:

public JsonResult GetTimelineJson()
{
    var result = new MyGraph([some data...]);

    return Json(JsonConvert.SerializeObject(result), JsonRequestBehavior.AllowGet);
}

结果:

"{\r\n  \"id\": \"myGraph\",\r\n  \"title\": \"Graph title\",\r\n [...]

任何企图把它包起来的一个HtmlString等,导致空集通过线路传递(尽管调试点显示它正确取消转义)。我检查的内容类型在HTTP头设置正确。

Any attempts to wrap it an an HtmlString, etc, result in an empty set being passed across the wire (though the debug point shows it correctly un-escaped). I've checked that the content-type is set correctly in the HTTP headers.

任何及所有帮助AP preciated,谢谢。

Any and all help appreciated, thanks.

推荐答案

对象已经被Json.NET系列化,当你把它传递给JSON(),它会连接codeD的两倍。如果必须使用Json.NET,而不是建在连接codeR,那么理想的方式来处理,这将是创建一个自定义的ActionResult接受对象,并调用Json.net内部序列化对象,并返回它作为一个应用程序/ JSON结果。

The object is already serialized by Json.NET, and when you pass it to Json() it gets encoded twice. If you must use Json.NET instead of the built in encoder, then the ideal way to handle this would be to create a custom ActionResult accepts the object and calls Json.net internally to serialize the object and return it as an application/json result.

修改

此code是对于上面提到的溶液。这是未经测试,但应该工作。

This code is for the solution mentioned above. It's untested, but should work.

public class JsonDotNetResult : ActionResult
{
    private object _obj { get; set; }
    public JsonDotNetResult(object obj)
    {
        _obj = obj;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.AddHeader("content-type", "application/json");
        context.HttpContext.Response.Write(JsonConvert.SerializeObject(_obj));
    }
}

和在你的控制器只是做:

and in your controller just do:

return new JsonDotNetResult(result);

这篇关于返回转义的Json在MVC与Json.Net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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