我得到了这个json:
{
"CountriesAndCities": [
{
"CountryId": 2,
"CountryName": "Chile",
"CountryISOA3": "CHL",
"Cities": [
{
"CityId": 26,
"CityName": "Gran Santiago",
"Country": null
},
{
"CityId": 27,
"CityName": "Gran Concepción",
"Country": null
}
]
}
]
}
如您所见,它是对象的列表,这些对象具有另一个列表。
我有这些模型:
public class City
{
public int CityId { get; set; }
public string CityName { get; set; }
public Country Country { get; set; }
}
public class Country
{
public int CountryId { get; set; }
public string CountryName { get; set; }
public string CountryISOA3 { get; set; }
public ICollection<City> Cities { get; set; }
}
现在,这可以解决问题:
public ICollection<Country> Countries { get; set; }
public RegionViewModel()
{
// Pidiendo las ciudades al backend.
S3EWebApi webApi = new S3EWebApi();
HttpResponseMessage response = webApi.Get("/api/Benefits/GetCountriesAndCities");
string jsonResponseString = response.Content.ReadAsStringAsync().Result;
JObject jsonResponse = JsonConvert.DeserializeObject<JObject>(jsonResponseString);
string countriesAndCitiesJSon = jsonResponse["CountriesAndCities"].ToString();
Countries = JsonConvert.DeserializeObject<List<Country>>(countriesAndCitiesJSon);
}
但我不知道,我认为这离优雅太远了。有更好的方法吗?谢谢。:)
一般来说,您绝对不需要两次应对。最简单的解决方案是将一堂课代表JSON的最外部部分,然后逐渐划分为@Alex Wiese的答案中所示。
如果您想在没有根类的情况下进行反序列化,则可以使用ToObject<T>()
方法进行 CC_1方法。
JObject jsonResponse = JsonConvert.DeserializeObject<JObject>(jsonResponseString);
Countries = jsonResponse["CountriesAndCities"].ToObject<List<Country>>();
为响应做包装类。
public class CountriesAndCitiesResponse
{
public List<Country> CountriesAndCities { get; set; }
}
然后像这样使用它:
public RegionViewModel()
{
// Pidiendo las ciudades al backend.
S3EWebApi webApi = new S3EWebApi();
HttpResponseMessage response = webApi.Get("/api/Benefits/GetCountriesAndCities");
string jsonResponseString = response.Content.ReadAsStringAsync().Result;
CountriesAndCitiesResponse response = JsonConvert.DeserializeObject<CountriesAndCitiesResponse>(jsonResponseString);
Countries = response.CountriesAndCities;
}
还应该重新考虑构造器中调用async
方法(可能导致死锁)。您可以考虑使用async Task Load()
方法中的呼叫,然后在调用构造函数后调用。