如何构造我的模型以匹配我的 JSON?

How to structure my models to match my JSON?

我是 API 的新手,我想使用提供给我的第三方 API(我无法控制他们如何构建数据)。我在 S.O 之前问过 post 但我不明白我应该做什么或怎么做他们的建议 'Structure your classes to match your JSON Object'

我的 Json 看起来像这样:

{
    "status": 1,
    "message": "",
    "data": {
        "VacationLeave": 11,
        "SickLeave": 10,
        "EmergencyLeave": 2,
        "HolidaySwap": 1,
        "OldLeave": 1
    }
}

我的控制器上有这个

public IActionResult APICall() 
{
    // Fetch the JSON string from URL.
    List<APIResponse> leaves = new List<APIResponse>();
    string apiUrl = "http://xxxxx.xxx.xxx/GetLeaveBalance/2170";

    HttpClient client = new HttpClient();
    HttpResponseMessage response = client.GetAsync(apiUrl).Result;

    if (response.IsSuccessStatusCode)
    {
        leaves = JsonConvert.DeserializeObject<List<APIResponse>>(response.Content.ReadAsStringAsync().Result);
    }

    // Return the Deserialized JSON object.
    return Json(leaves);
}

我的模型类:

public class APIResponse : LeaveModel
{
    public int Status { get; set; }
    public string Message { get; set; }

    public List<LeaveModel> Leaves;
}

public class LeaveModel
{
    public int VacationLeave { get; set; }
    public int SickLeave { get; set; }
    public int EmergencyLeave { get; set; }
    public int HolidaySwap { get; set; }
    public int OldSwap { get; set; }
}

我的问题是:我收到此错误:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[APITest.Models.APIResponse]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

任何人都可以帮我解决我在这里遗漏的问题吗?

谢谢

根据 json ApiResponse class 必须如下所示

 public class APIResponse : LeaveModel
{
    public int Status { get; set; }
    public string Message { get; set; }

    public LeaveModel data;
}

您的 APIResponse 应该支持泛型。

public class APIResponse<T>
{
    public int Status { get; set; }
    public string Message { get; set; }

    public T Data { get; set; }
}

因为 data 是一个 LeaveModel 对象而不是 LeaveModel 数组。

并反序列化为 APIResponse<LeaveModel> 类型。

APIResponse<LeaveModel> apiResponse = JsonConvert.DeserializeObject<APIResponse<LeaveModel>>(response.Content.ReadAsStringAsync().Result);
LeaveModel leave = apiResponse.Data;

并建议将方法更改为异步。

public async Task<IActionResult> APICallAsync() 
{
    //Fetch the JSON string from URL.
    LeaveModel leave = new LeaveModel();
    string apiUrl = "http://xxxxx.xxx.xxx/GetLeaveBalance/2170";

    HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.GetAsync(apiUrl);
    if (response.IsSuccessStatusCode)
    {
        APIResponse<LeaveModel> apiResponse = JsonConvert.DeserializeObject<APIResponse<LeaveModel>>(await response.Content.ReadAsStringAsync());  
        leave = apiResponse.Data;        
    }

    //Return the Deserialized JSON object.
    return Json(leave);
}