加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 将JSON对象作为参数传递给MVC控制器

发布时间:2020-12-16 07:11:59 所属栏目:asp.Net 来源:网络整理
导读:我有以下任意 JSON对象(字段名称可能会更改). { firstname: "Ted",lastname: "Smith",age: 34,married : true } – public JsonResult GetData(??????????){...} 我知道我可以像JSON对象一样定义一个具有与参数相同的字段名称的类,但我希望我的控制器能够接
我有以下任意 JSON对象(字段名称可能会更改).

{
    firstname: "Ted",lastname: "Smith",age: 34,married : true
  }

public JsonResult GetData(??????????){
.
.
.
}

我知道我可以像JSON对象一样定义一个具有与参数相同的字段名称的类,但我希望我的控制器能够接受具有不同字段名称的任意JSON对象.

解决方法

如果您想将自定义JSON对象传递给MVC操作,那么您可以使用此解决方案,它就像一个魅力.

public string GetData()
    {
        // InputStream contains the JSON object you've sent
        String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();

        // Deserialize it to a dictionary
        var dic = 
          Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<String,dynamic>>(jsonString);

        string result = "";

        result += dic["firstname"] + dic["lastname"];

        // You can even cast your object to their original type because of 'dynamic' keyword
        result += ",Age: " + (int)dic["age"];

        if ((bool)dic["married"])
            result += ",Married";


        return result;
    }

此解决方案的真正好处是您不需要为每个参数组合定义新类,除此之外,您可以轻松地将对象转换为其原始类型.

更新

现在,你甚至可以合并你的GET和POST动作方法,因为你的post方法不再有任何参数,就像这样:

public ActionResult GetData()
 {
    // GET method
    if (Request.HttpMethod.ToString().Equals("GET"))
        return View();

    // POST method 
    .
    .
    .

    var dic = GetDic(Request);
    .
    .
    String result = dic["fname"];

    return Content(result);
 }

并且您可以使用这样的帮助方法来促进您的工作

public static Dictionary<string,dynamic> GetDic(HttpRequestBase request)
{
    String jsonString = new StreamReader(request.InputStream).ReadToEnd();
    return Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,dynamic>>(jsonString);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读