【问题标题】:JSON request to ASP.NET API对 ASP.NET API 的 JSON 请求
【发布时间】:2020-01-09 01:37:49
【问题描述】:

我有以下 JSON 数据:

{
    "0": {
        "id": 0,
        "type": "camera",
        "option": [
            {
                "optionId": 1,
                "optionValue": "",
                "answered": "false",
                "lastanswerd": "false"
            }
        ]
    },
    "1": {
        "id": 1,
        "type": "checkCategory",
        "option": [
            {
                "optionId": 1,
                "optionValue": "",
                "answered": "false",
                "lastanswerd": "false"
            },
            {
                "optionId": 2,
                "optionValue": "",
                "answered": "false",
                "lastanswerd": "false"
            }           
        ]
    }
}

如何在控制器动作中使用哪种类型的参数将 JSON 数据传递到 ASP.NET API 请求中?

【问题讨论】:

    标签: json asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    Asp.net MVC 自动映射并尝试转换每个 key:value 的 json。

    {"key1":"value", "key2":"value"}
    

    您可以使用函数内的参数访问这些值

    public ActionResult Index(string key,string key2)
    

    或者创建一个公共设置器等于你的键和无参数构造器的类。

    public Class MyJson
    {
        public string key1 {get;set;}
        public string key2 {get;set;}
    }
    
    public ActionResult Index(MyJson model)
    

    在您的特定情况下,您传递了一个对象列表,因此您应该使用

    public ActionResult Index(List<MyJson> model)
    

    【讨论】:

      【解决方案2】:

      如果您将 json 更改为:

      [
        {
          "id": 0,
          "type": "camera",
          "option": [
            {
              "optionId": 1,
              "optionValue": "",
              "answered": "false",
              "lastanswerd": "false"
            }
          ]
        },
        {
          "id": 1,
          "type": "checkCategory",
          "option": [
            {
              "optionId": 1,
              "optionValue": "",
              "answered": "false",
              "lastanswerd": "false"
            },
            {
              "optionId": 2,
              "optionValue": "",
              "answered": "false",
              "lastanswerd": "false"
            }
          ]
        }
      ]
      

      json2csharp 给我们:

      public class Option
      {
          public int optionId { get; set; }
          public string optionValue { get; set; }
          public string answered { get; set; }
          public string lastanswerd { get; set; }
      }
      
      public class RootObject
      {
          public int id { get; set; }
          public string type { get; set; }
          public List<Option> option { get; set; }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-07-14
        • 2023-03-09
        • 1970-01-01
        • 2020-08-22
        • 1970-01-01
        • 2019-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多