您的位置:首页 > Web前端 > JavaScript

Returning unescaped Json in MVC with Json.Net

2014-06-28 02:45 399 查看
http://stackoverflow.com/questions/7382265/returning-unescaped-json-in-mvc-with-json-net

1.

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.

EDIT

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


2.

You are Jsoning it twice, the
Json
method
is json serializing your already converted string. If you want to use JsonConvert then write that directly to the response stream.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: