我使用的是ASP MVC 5。我在一个控制器中有一个返回json对象的操作:
[HttpGet]
public JsonResult GetUsers()
{
return Json(....., JsonRequestBehavior.AllowGet);
}现在我想使用JSON.Net库,我看到在ASPMVC5中还没有出现。实际上,我可以写
using Newtonsoft.Json;而不从NuGet导入库。
现在我试着写:
public JsonResult GetUsers()
{
return JsonConvert.SerializeObject(....);
}但是我在编译过程中有一个错误:我不能将返回类型字符串转换为JsonResult。如何在操作中使用Json.NET?操作的正确返回类型是什么?
发布于 2016-11-10 09:50:49
我更喜欢创建一个能产生自定义ActionResult的object扩展,因为它可以在返回对象时内联应用于任何对象
下面扩展使用Newtonsoft Nuget来序列化忽略空属性的对象
public static class NewtonsoftJsonExtensions
{
public static ActionResult ToJsonResult(this object obj)
{
var content = new ContentResult();
content.Content = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
content.ContentType = "application/json";
return content;
}
}下面的示例演示了如何使用该扩展。
public ActionResult someRoute()
{
//Create any type of object and populate
var myReturnObj = someObj;
return myReturnObj.ToJsonResult();
}好好享受吧。
发布于 2015-12-04 23:00:28
您可以使用ContentResult,如下所示:
return Content(JsonConvert.SerializeObject(...), "application/json");发布于 2015-12-04 23:02:03
public string GetAccount()
{
Account account = new Account
{
Email = "james@example.com",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List<string>
{
"User",
"Admin"
}
};
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
return json;
}或
public ActionResult Movies()
{
var movies = new List<object>();
movies.Add(new { Title = "Ghostbusters", Genre = "Comedy", Year = 1984 });
movies.Add(new { Title = "Gone with Wind", Genre = "Drama", Year = 1939 });
movies.Add(new { Title = "Star Wars", Genre = "Science Fiction", Year = 1977 });
return Json(movies, JsonRequestBehavior.AllowGet);
}https://stackoverflow.com/questions/34091056
复制相似问题