2014-04-28 79 views
39

我想寫一個C#方法,將序列化模型並返回JSON結果。這裏是我的代碼:使用JSON.NET返回ActionResult

public ActionResult Read([DataSourceRequest] DataSourceRequest request) 
    { 
     var items = db.Words.Take(1).ToList(); 
     JsonSerializerSettings jsSettings = new JsonSerializerSettings(); 
     jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; 
     var converted = JsonConvert.SerializeObject(items, null, jsSettings); 
     return Json(converted, JsonRequestBehavior.AllowGet); 
    } 

我得到了以下JSON結果時,我去字/讀在Chrome:

"[{\"WordId\":1,\"Rank\":1,\"PartOfSpeech\":\"article\",\"Image\":\"Upload/29/1/Capture1.PNG\",\"FrequencyNumber\":\"22038615\",\"Article\":null,\"ClarificationText\":null,\"WordName\":\"the | article\",\"MasterId\":0,\"SoundFileUrl\":\"/UploadSound/7fd752a6-97ef-4a99-b324-a160295b8ac4/1/sixty_vocab_click_button.mp3\",\"LangId\":1,\"CatId\":null,\"IsActive\":false} 

我認爲\」轉義引號是發生當您雙擊序列化問題一個對象和其他問題: WCF JSON output is getting unwanted quotes & backslashes added

這肯定看起來像我雙序列化我的對象,因爲我第一次使用序列化和JSON.NET然後我的結果傳遞到JSON()函數,我需要手動序列化。避免d referenceloops,但我認爲我的View需要一個ActionResult。

如何在這裏返回ActionResult?我需要,還是隻能返回一個字符串?

+0

在JavaScript返回我只是做JSON.parse(消息);。 – MiniRagnarok

+0

您的意思是使用Javascript解析出/「s?我正在使用Razor HTML幫助程序進行特定的包裝,所以我不知道如何讓它工作.. – hubatish

回答

60

我發現了一個類似計算器的問題: Json.Net And ActionResult

答案有使用

return Content(converted, "application/json"); 

那似乎是我最簡單的網頁上工作建議。

+4

IMO最好的答案。簡單,並完成所要求的。 – pimbrouwers

+2

如果你要檢查標題,你會看到你可能有'text/html'作爲內容類型。 – Dementic

+0

迄今爲止最簡單的解決方案。這正是它需要的。 – user1751825

59

不是使用JSON.NET進行序列化,而是調用Json(),爲什麼不改寫控制器中的Json()方法(或者可能是基本控制器來增強其可重用性)?

這是從這個博客post拉。

在您的控制器(或基本控制器):

protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior) 
{ 
    return new JsonNetResult 
    { 
     Data = data, 
     ContentType = contentType, 
     ContentEncoding = contentEncoding, 
     JsonRequestBehavior = behavior 
    }; 
} 

而對於JsonNetResult定義:

public class JsonNetResult : JsonResult 
{ 
    public JsonNetResult() 
    { 
     Settings = new JsonSerializerSettings 
     { 
      ReferenceLoopHandling = ReferenceLoopHandling.Ignore, 
     }; 
    } 

    public JsonSerializerSettings Settings { get; private set; } 

    public override void ExecuteResult(ControllerContext context) 
    { 
     if (context == null) 
      throw new ArgumentNullException("context"); 
     if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) 
      throw new InvalidOperationException("JSON GET is not allowed"); 

     HttpResponseBase response = context.HttpContext.Response; 
     response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType; 

     if (this.ContentEncoding != null) 
      response.ContentEncoding = this.ContentEncoding; 
     if (this.Data == null) 
      return; 

     var scriptSerializer = JsonSerializer.Create(this.Settings); 

     using (var sw = new StringWriter()) 
     { 
      scriptSerializer.Serialize(sw, this.Data); 
      response.Write(sw.ToString()); 
     } 
    } 
} 

通過這樣做,當你在你的控制器調用Json(),您將自動獲得JSON.NET序列化你想要的。

+0

很酷,這很方便。 ,我想這會讓我仍然通過JSONRequestBehavior.AllowGet,但它似乎不工作。 – hubatish

+0

爲了得到這個工作,你需要添加覆蓋到'Json()',通過默認其他參數值。這是默認的實現做什麼。 –

+0

那麼,這條線 JSON(對象數據串的contentType,System.Text.Encoding contentEncoding,JsonRequestBehavior行爲) 似乎意味着我可以做JSON(轉換,JsonRequestBehavior.AllowGet);但是當我進入頁面時,我得到了「允許GET請求,將JsonRequestBehavior設置爲AllowGet」。 – hubatish