Can't figure out how to store data from API call

293 Views Asked by At

This is my first time asking a question. I've been trying to get this working for too long. I've looked over some similar posts but just can't quite crack it.

I'm trying to make an API call in c# using flurl. I can make the call, but can't figure out how to store the data.

Here is an example of the response from the call made using powershell:

StatusCode        : 200
StatusDescription : OK
Content           : {
  "result": [
    {
      "apiUserName": "[email protected]",
      "apiPassword": "dk65dss5s5HH",
      "id": "d38a1ea4-46d1-46b7-87a2-46c09da663eb",
      "name": "catHotel",
      "applUrl": "https://catshotel.somedomain.com/manager/",
      "apiUrl": "https://catshotel.somedomain.com/API/",
      "stateId": 2,
      "databaseName": null,
      "databaseServerName": null
    },
    {
      "apiUserName": "[email protected]",
      "apiPassword": "dhh7k33kDDh5g",
      "id": "00d5e97b-5ea6-47dd-b920-8678f949c51f",
      "name": "possumLodge",
      "applUrl": "https://possumlodge.somedomain.com/manager/",
      "apiUrl": "https://possumlodge.somedomain.com/API/",
      "stateId": 1,
      "databaseName": "customer-datab",
      "databaseServerName": "customersDBserv.somedomain.com"
    }
  ],
  "targetUrl": null,
  "success": true,
  "error": null,
  "unAuthorizedRequest": false,
  "__abp": true
}

RawContent        : HTTP/1.1 200 OK
                    Cache-Control: no-store, must-revalidate, no-cache, max-age=0
                    Request-Context: appId=cid-v1:8cgg58f2-5212-4685-b45f-149104d7a5be
                    Access-Control-Expose-Headers: Request-Context
                    X-Fr…
Headers           : {[Cache-Control, System.String[]], [Request-Context, System.String[]], [Access-Control-Expose-Headers, System.String[]], [X-Frame-Options, System.String[]]…}
Images            : {}
InputFields       : {}
Links             : {}
RawContentLength  : 23638
RelationLink      : {}

In c#, I've made a class: -

 class Facilities
    {
        public string Name { get; set; }
    }

And then I make the call: -

List<facilities> facilities = await url.WithHeaders(new { Accept = "Application/json", Authorization = token }).GetJsonAsync<List<facilities>>();

But I get errors such as:-

"Message "Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ConsoleApp2.facilities]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'result', line 1, position 10." string"

I can't figure out how to store each 'facility' into an array of facilities :(

2

There are 2 best solutions below

0
On

You can use a System.Dynamic namespace Then deserialize it like so:

var responseContent = response.Content;
var responseString = responseContent.ReadAsStringAsync().Result;

dynamic projects = JArray.Parse(responseString) as JArray;

the controller action needs to return VIEW(project) lastly, your View page needs to use @model dynamic

0
On

I'm Not an Expert here and Can't say i know about flurl, so i looked here https://jonathancrozier.com/blog/calling-all-apis-how-to-use-flurl-with-c-sharp

and looked into the error message and as the message say, your strongly-typed model need to match the Json object, so that the deserialization mechanism in flurl can deserialize the Json objects that match your strongly-typed model properties, meaning your class Facilities should look something like this.

    class Facilities
    {
        public string apiUserName { get; set; }
        public string apiPassword { get; set; }
        public int id { get; set; }
        public string name { get; set; }
        public string applUrl { get; set; }
        public string apiUrl { get; set; }
        public int stateId { get; set; }
        public string databaseName { get; set; }
        public string databaseServerName { get; set; }
    }

And try using

    var facilities = await url.WithHeaders....

so you can figure out what can of object you are getting.

Note: I mimicked your request code using the Package Flurl.Http v2.4.2, with this code

        using Flurl;
        using Flurl.Http;

        var token = "SomeToken1234";
        Url url = "https://jsonplaceholder.typicode.com/todos";
        List<Todo> todos = await url.WithHeaders(new { Accept = "application/json", Authorization = token }).GetJsonAsync<List<Todo>>();

this here work, you can test it, maybe it's something regard the version you use.