簡體   English   中英

對 ASP.NET API 的 JSON 請求

[英]JSON request to ASP.NET API

我有以下 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 更改為:

[
  {
    "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; }
}

Asp.net MVC 自動映射並嘗試轉換每個鍵:json 的值。

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

您可以在函數中使用 params 訪問這些值

public ActionResult Index(string key,string key2)

或者創建一個公共 setter 等於你的鍵和一個無參數構造函數的類。

public Class MyJson
{
    public string key1 {get;set;}
    public string key2 {get;set;}
}

public ActionResult Index(MyJson model)

在您的特定情況下,您傳遞了一個對象列表,因此您應該使用

public ActionResult Index(List<MyJson> model)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM