ASP.NET MVC - Replacing MVC JavascriptSerializer with JSON.NET JsonSerializer

使用 ASP.NET MVC 或是 Web API 做 JSON 格式的回傳,只要將 Model 帶入去建構 JsonResult 物件回傳即可,像是下面這樣:

1
2
3
...
return new JsonResult(model);
...


這樣的寫法預設會採用 JavaSriptSerializer 去做 JSON 的序列化,有著效能不佳的問題,且序列化出來的資料有時也不是我們所期望的,像是 DateTime 物件會被序列化成下面這樣:

"/Date(1290181373164)/"

Json.Net 提供了 JsonNetResult 可解決這樣的問題,可將程式直接加到專案內使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/// <summary> 
/// Simple Json Result that implements the Json.NET serialiser offering more versatile serialisation
/// </summary>
public class JsonNetResult : ActionResult
{
public JsonNetResult()
{
}

public JsonNetResult (object responseBody)
{
ResponseBody = responseBody;
}

public JsonNetResult(object responseBody, JsonSerializerSettings settings)
{
Settings = settings;
}

/// <summary>Gets or sets the serialiser settings</summary>
public JsonSerializerSettings Settings { get; set; }

/// <summary>Gets or sets the encoding of the response</summary>
public Encoding ContentEncoding { get; set; }

/// <summary>Gets or sets the content type for the response</summary>
public string ContentType { get; set; }

/// <summary>Gets or sets the body of the response</summary>
public object ResponseBody { get; set; }

/// <summary>Gets the formatting types depending on whether we are in debug mode</summary>
private Formatting Formatting
{
get
{
return Debugger.IsAttached ? Formatting.Indented : Formatting.None;
}
}

/// <summary>
/// Serialises the response and writes it out to the response object
/// </summary>
/// <param name="context">The execution context</param>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}

HttpResponseBase response = context.HttpContext.Response;

// set content type
if (!string.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}

// set content encoding
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}

if (ResponseBody != null)
{
response.Write(JsonConvert.SerializeObject(ResponseBody, Formatting, Settings));
}
}
}


使用上把本來的 JsonResult 替換成 JsonNetResult 就可以了。

1
2
3
...
return new JsonNetResult(model);
...


或是撰寫基底的 Controller 來處理也可以。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class BaseController:Controller
{
protected internal override JsonResult Json(object data)
{
return new JsonNetResult(data);
}
}

public class MyController:BaseController
{
...
return Json(model);
...
}