In an MVVM pattern I'm trying to make an async method that fetches a json string, and returns the result as a List<Cabinet> so that I can use this list later.
I have json that looks like this, it represents a list of cabinet object:
{"cabinets":[{"id":"1","longitudeGPS":"2,2891506","latitudeGPS":"48,8618687","cp":"75016","ville":"Paris","rue":"1 Avenue Gustave V de Su\u00e8de"},{"id":"2","longitudeGPS":"3,0566481","latitudeGPS":"50,6302592","cp":"59800","ville":"Lille","rue":"127 Rue Solf\u00e9rino"},{"id":"3","longitudeGPS":"3,8749271","latitudeGPS":"43,6110374","cp":"34000","ville":"Montpellier","rue":"17 Rue Foch"},{"id":"4","longitudeGPS":"-1,6736931","latitudeGPS":"48,1181043","cp":"35700","ville":"Rennes","rue":"127 23 Rue de Vincennes"},{"id":"5","longitudeGPS":"0,0991065","latitudeGPS":"49,4931952","cp":"76600","ville":"Le Havre","rue":"32 Avenue Foch"},{"id":"6","longitudeGPS":"4,8353320","latitudeGPS":"45,7639021","cp":"69002","ville":"Lyon","rue":"27 Rue Henri Germain"}]}
I've created the classes according to json2csharp generator:
public class Cabinet
{
public string id { get; set; }
public string longitudeGPS { get; set; }
public string latitudeGPS { get; set; }
public string cp { get; set; }
public string ville { get; set; }
public string rue { get; set; }
}
public class CabinetList
{
public List<Cabinet> cabinets { get; set; }
}
Here I have an HttpClient that fetches the json from the website and stores it in a listCabinet variable.
public string adresseCabinets = "http://ppe3JoJuAd/gsbAppliFraisV2/webservices/w_cabinet.php";
public static string userId;
CabinetsList listeCabinets = new CabinetsList();
public async Task<List<CabinetsList>>loadCabinets()
{
HttpClient clientCabinets = new HttpClient();
var response = await clientCabinets.GetAsync(adresseCabinets);
var json = response.Content.ReadAsStringAsync().Result;
listeCabinets = JsonConvert.DeserializeObject<CabinetsList>(json);
}
When I want to return the listeCabinets variable I have the following error: cannot implicitly convert type cabinetList to System.Collection.Generic.List CabinetList
How can I solve this?
awaittheReadAsStringAsynctoo?.Resultwhich is bad practice, useawaitinstead like before.listeCabinetsis of typeCabinetList, and your return value should be of typeList<CabinetsList>. You'll need to convertCabinetsListtoList<Cabinet>.public async Task<CabinetsList> loadCabinets()