ASP.NET MVC5中Json(JToken.Parse)返回空数组如何解决?
问题根因
ASP.NET MVC 5 自带的 Json() 方法默认使用 JavaScriptSerializer 完成序列化,该序列化器无法识别 Newtonsoft.Json 提供的 JObject/JToken 类型,会错误序列化其内部嵌套结构,因此返回了你看到的空嵌套数组响应。而 ASP.NET Core 2.x 默认集成 Newtonsoft.Json 作为序列化器,所以同一段代码可以正常运行。
解决方案
以下三种方案按实现复杂度从低到高排列,按需选择即可:
方案1:直接返回JSON字符串(最简单)
你已经通过 ReadAsStringAsync() 拿到了符合要求的完整JSON字符串,不需要额外序列化/反序列化,直接返回 ContentResult 并指定正确的Content-Type即可:
public ActionResult YourActionName() { // 原有HttpClient调用逻辑 string jsonResponse = response.Content.ReadAsStringAsync().Result; // 直接返回原始JSON,指定Content-Type为application/json return Content(jsonResponse, "application/json"); }
方案2:反序列化为强类型后返回
如果需要在后端对响应内容做逻辑处理,可以先定义匹配结构的强类型,再用 Json() 方法返回:
步骤1:定义实体类
public class ApiErrorItem { public string errorCode { get; set; } public string errorMessage { get; set; } } public class ApiResponse { public int responseCode { get; set; } public List<ApiErrorItem> errors { get; set; } }
步骤2:反序列化后返回
public ActionResult YourActionName() { // 原有HttpClient调用逻辑 string jsonResponse = response.Content.ReadAsStringAsync().Result; // 反序列化为强类型对象 var result = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResponse>(jsonResponse); // MVC5如果是GET请求返回JSON,必须加JsonRequestBehavior.AllowGet参数 return Json(result, JsonRequestBehavior.AllowGet); }
方案3:自定义支持Newtonsoft.Json的JsonResult
如果你确实需要使用 JObject/JToken 类型做动态处理,可以自定义基于Newtonsoft.Json的JsonResult替换默认实现:
步骤1:定义自定义JsonResult类
public class NewtonsoftJsonResult : JsonResult { public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && context.HttpContext.Request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("不允许GET请求获取JSON数据"); } var response = context.HttpContext.Response; response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType; if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; if (Data != null) { // 使用Newtonsoft.Json完成序列化 response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(Data)); } } }
步骤2:在Action中返回自定义结果
public ActionResult YourActionName() { // 原有HttpClient调用逻辑 string jsonResponse = response.Content.ReadAsStringAsync().Result; var jObj = Newtonsoft.Json.Linq.JObject.Parse(jsonResponse); // 返回自定义的NewtonsoftJsonResult return new NewtonsoftJsonResult() { Data = jObj, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; }
内容的提问来源于stack exchange,提问作者Ranjith
相关产品推荐
相关产品推荐

