简体   繁体   中英

Blazor Rest Api call using httpClient.GetJsonAsync Errors

I am trying to make a call to a Rest API from Blazor Server Application using the following call to get a list of projects. The API returns correctly but it cannot map to the Project Object because the JSON for the projects is nested under a results property.

This is the call I am making

var projects = await httpClient.GetJsonAsync<Project[]>("projects");

And this is what the response from the API call looks like.

{
  "message": "GET Request successful.",
  "isError": false,
  "result": [
    {
      "projectCode": "PRJ-1996",
      "businessAssociateID": "BA000000000002",
      "contractStartDate": "11/19/2020 8:37:17 AM",
      "contractEndDate": "11/19/2020 8:37:17 AM",
      "contractStatus": "Active",
      "createdBy": "system",
      "createdDate": "2020-11-19T08:37:17.37",
      "active": true
    },
    {
      "projectCode": "PRJ-1997",
      "businessAssociateID": "BA000000000002",
      "contractStartDate": "11/19/2020 8:37:17 AM",
      "contractEndDate": "11/19/2020 8:37:17 AM",
      "contractStatus": "Active",
      "createdBy": "system",
      "createdDate": "2020-11-19T08:37:17.37",
      "active": true
    },
    {
      "projectCode": "PRJ-1998",
      "businessAssociateID": "BA000000000002",
      "contractStartDate": "11/19/2020 8:37:17 AM",
      "contractEndDate": "11/19/2020 8:37:17 AM",
      "contractStatus": "Active",
      "createdBy": "system",
      "createdDate": "2020-11-19T08:37:17.37",
      "active": true
    },
    {
  ]
}

How can I use the GetJsonAsync function to map to the Projects list. All the examples that I have seen only return the array of objects without the response messages.

This is the error I receive on the call. The routes are correct to the API call as well as that was already tested.

JsonException: The JSON value could not be converted to Web.Data.Project[]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.

The quick and easy way out would be

class Response
{
   public string  Message { get; set; }
   public bool  IsError { get; set; }
   public Project[] Result { get; set; }
}  

This lets you have a look at IsError and Message too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM