我使用的是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?动作的正确返回类型是什么?
我更喜欢创建一个object
扩展,它可以产生自定义的ActionResult
,因为当返回时,它可以内联应用于任何对象
bellow扩展使用Newtonsoft Nuget来序列化忽略null属性的对象
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();
}
享受吧。
您可以像这样使用ContentResult
:
return Content(JsonConvert.SerializeObject(...), "application/json");
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);
}
您基本上需要编写一个自定义ActionResult,如本文中所示
[HttpGet]
public JsonResult GetUsers()
{
JObject someData = ...;
return new JSONNetResult(someData);
}
JSONNetResult函数为:
public class JSONNetResult: ActionResult
{
private readonly JObject _data;
public JSONNetResult(JObject data)
{
_data = data;
}
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "application/json";
response.Write(_data.ToString(Newtonsoft.Json.Formatting.None));
}
}
您可能需要考虑使用IHttpActionResult,因为这将自动为您提供序列化的好处(或者您可以自己进行),但也允许您在函数中发生错误、异常或其他事情时控制返回的错误代码。
// GET: api/portfolio'
[HttpGet]
public IHttpActionResult Get()
{
List<string> somethings = DataStore.GetSomeThings();
//Return list and return ok (HTTP 200)
return Ok(somethings);
}