5

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

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

-

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

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

4

3 回答 3

6

如果你想将自定义 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);
}
于 2012-08-23T06:27:28.903 回答
1

拥有一个具有相同签名的 ViewModel 并将其用作参数类型。然后模型绑定将起作用

public class Customer
{
  public string firstname { set;get;}
  public string lastname { set;get;}
  public int age{ set;get;} 
  public string location{ set;get;}
   //other relevant proeprties also
}

你的 Action 方法看起来像

public JsonResult GetData(Customer customer)
{
  //check customer object properties now.
}
于 2012-08-22T16:50:59.047 回答
0

你也可以在 MVC 4 中使用它

public JsonResult GetJson(Dictionary<string,string> param)
{
    //do work
}
于 2014-01-15T08:53:35.113 回答