1

我需要将以下 json 对象传递给我的 asp.net core 3.1 web api

{
    "client": {
        "clientID": "3529",
        "clientData": "This a test data"
    },
    "selectedUserIDs": [
        3549,
        3567,
        3546,
        3561,
        3532       
    ],
    "selectedDepartmentsIDs": [
        10695,
        71,
        72,
        121     
       
    ]
}

现在我如何在我的 web api 中访问这个对象?以下是我的 api 控制器

[HttpPost("/api/client/{id}/savedata")]
public ActionResult SaveClientDetails(int workflowID, [FromBody] Clientdata data)
{            
    //save operation        
}

以下是我的客户数据类

public class clientdata
{
    public client client{ get; set; }
    public List<selectedUserIDs> selectedUserIDs{ get; set; }
    public List<selectedDepartmentsIDs> selectedDepartmentsIDs { get; set; }
}

和客户端类

public class client 
{
    public string clientID { get; set; }
    public string clientData { get; set; }
}

和 selectedUserIDs 类如下

public class selectedUserIDs
{        
    public int Ids{ get; set; }
}

和 selectedDepartmentsIDs 类如下

public class selectedDepartmentsIDs
{        
    public int Ids{ get; set; }
}

但我无法在 web api body 中访问这个复杂的对象

在邮递员中抛出以下错误

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|10eabbbb-4a15387d9152b7d6.",
    "errors": {
        "$.selectedUserIDs[0]": [
            "The JSON value could not be converted to System.Collections.Generic.List`1[ClientCoreAPI.Client.Entity.selectedUserIDs]. Path: $.selectedUserIDs[0] | LineNumber: 6 | BytePositionInLine: 12."
        ]
    }
}
4

1 回答 1

2

您的定义clientdata与 json 文件不匹配。你有两个选择:

  1. 更改clientdata为:

     public class clientdata
     {
         public client client{ get; set; }
         public List<int> selectedUserIDs{ get; set; }
         public List<int> selectedDepartmentsIDs { get; set; }
     }
    
  2. 或者把json改成

    {
        "client": {
            "clientID": "3529",
            "clientData": "This a test data"
        },
        "selectedUserIDs": [
            { "Ids": 3549 },
            { "Ids": 3567 },
            { "Ids": 3546 },
            { "Ids": 3561 },
            { "Ids": 3532 }       
        ],
        "selectedDepartmentsIDs": [
            { "Ids": 10695 },
            { "Ids": 71 },
            { "Ids": 72 },
            { "Ids": 121 }
        ]
    }
    
于 2020-08-05T13:25:41.270 回答