ASP MVC 5和Json.NET:操作返回类型 [英] ASP MVC 5 and Json.NET: action return type

查看:89
本文介绍了ASP MVC 5和Json.NET:操作返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP MVC5.我在返回json对象的控制器中有一个动作:

i'm using ASP MVC 5. I have an action in a controller that return a json object:

[HttpGet]
public JsonResult GetUsers()
{
  return Json(....., JsonRequestBehavior.AllowGet);
}

现在,我想使用JSON.Net库,并且看到ASP MVC 5中仍存在该库.实际上我可以写

Now i want to use the JSON.Net library and i see that in ASP MVC 5 is yet present. In effect i can write

using Newtonsoft.Json;

不从NuGet导入库.

without import the library from NuGet.

现在我试图写:

public JsonResult GetUsers()
{
    return JsonConvert.SerializeObject(....);
}

但是在编译过程中出现错误:我无法将返回类型字符串转换为JsonResult. 如何在动作中使用Json.NET?动作的正确返回类型是什么?

But i have an error during compilation: I cann't convert the return type string to JsonResult. How can i use the Json.NET inside an action? What is the correct return type of an action?

推荐答案

我更喜欢创建对象扩展来创建自定义操作结果,这就是我选择的原因...

I prefer to create an object extension to create a custom Action Result, and this is the reason for my choose...

对象扩展(我的具体情况,我正在用newtonsoft进行序列化,而忽略空值:

The Object Extension (My specific case, i am serializing with newtonsoft and ignoring null values:

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

它真的很容易使用,将其可扩展性扩展到任何对象,因此要使用u,只需要它即可:

And it's really easy to use, sinse its extensible to any object, so to use u just need it:

    public ActionResult someRoute()
    {
        //Create any type of object and populate
        var myReturnObj = someObj;
        return myReturnObj.ToJsonResult();
    }

希望对所有人有帮助

这篇关于ASP MVC 5和Json.NET:操作返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆