gpt4 book ai didi

asp.net-mvc - 将 JSON 对象作为参数传递给 MVC Controller

转载 作者:行者123 更新时间:2023-12-02 05:42:15 25 4
gpt4 key购买 nike

我有以下任意 JSON 对象(字段名称可能会更改)。

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

-

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

我知道我可以像 JSON 对象一样定义一个类,其字段名称与参数相同,但我希望我的 Controller 接受具有不同字段名称的任意 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);
}

关于asp.net-mvc - 将 JSON 对象作为参数传递给 MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12069171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com