【问题标题】:Json.Net And ActionResultJson.Net 和 ActionResult
【发布时间】:2014-03-23 05:33:54
【问题描述】:

我自己构建了一个 JObject,并希望将其作为 ActionResult 返回。我不想创建然后序列化数据对象

例如

public ActionResult Test(string id)
{
      var res = new JObject();
      JArray array = new JArray();
      array.Add("Manual text");
      array.Add(new DateTime(2000, 5, 23));
      res["id"] = 1;
      res["result"] = array;
      return Json(res); //???????
}

【问题讨论】:

  • @Liam 这个问题是第一位的,那么它怎么可能是重复的?您标记了错误的问题。

标签: c# asp.net-mvc json json.net


【解决方案1】:

您应该能够在您的操作方法中执行此操作:

return Content( res.ToString(), "application/json" );

【讨论】:

  • 我试图使用 Newtonsoft Json Serializer 来解决日期时间问题,但不知道如何返回我拥有的字符串。非常感谢
  • This 看起来是一种更强大的处理方式。另外,您不必将类型从 JsonResult 更改为 ActionResult
  • @jpaugh,这个帖子已经有四年多了。今天处理这个问题的更好方法是使用 Web API,而不是弯曲 MVC 框架来构建本质上是 REST API 的东西。另外,我不明白你陈述的第二部分。 JsonResult 是 ActionResult 的子类。最后,编写更多代码来完成框架会自动为您完成的工作绝不是 IMO 的好解决方案。
  • Newtonsoft 的 JSON.NET 克服了内置 JSON 序列化程序的许多限制,因此这个主题仍然相关。 (而且,虽然我无法更改我所使用的技术堆栈版本,但我确信我不是唯一一个落后于曲线 4(或更多)年的人。)
  • 我的第二个语句是指表达式的结果类型,即上面的ContentResult;而我已经在使用JsonResult
【解决方案2】:

如果您处理 JSON 格式,只需 return JSON Formatted string

public string Test(string id)
{
      var res = new JObject();
      JArray array = new JArray();
      array.Add("Manual text");
      array.Add(new DateTime(2000, 5, 23));
      res["id"] = 1;
      res["result"] = array;
      return YourJSONSerializedString;
}

否则使用内置JsonResult(ActionResult)

    public JsonResult Test(string id)
    {

          return Json(objectToConvert);
    }

【讨论】:

  • 响应内容类型和您需要填写以准备正确响应的其他内容如何?你确定我可以扔字符串吗?
  • 我们需要添加内容类型
猜你喜欢
  • 2014-06-14
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多