使用JSON.NET返回ActionResult

我想写一个C#方法,将序列化模型,并返回一个JSON结果。 这是我的代码:

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

当我转到Chrome中的Words / Read时,我得到了以下JSON结果:

 "[{\"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输出得到不需要的引号和反斜杠添加

它绝对看起来像我双连载我的对象,因为我第一次使用JSON.NET序列化,然后将我的结果传递到Json()函数。 我需要手动序列化,以避免referenceloops,但我认为我的视图需要一个ActionResult。

我怎样才能在这里返回一个ActionResult? 我需要,还是只能返回一个string?

而不是序列化使用JSON.NET,然后调用Json() ,而不是重写控制器中的Json()方法(或者基本控制器,以提高其可重用性)?

这是从这个博客文章拉。

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

 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序列化。

我发现了一个类似的stackoverflow问题: Json.Net和ActionResult

那里的答案build议使用

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

这似乎在我的非常简单的页面上工作。