2017-12-18 6 views
3

나는이 JSON 가지고 :가장 좋은 방법은 JSON에서 중첩 된 목록을 역 직렬화하는 - C#

당신이 볼 수 있듯이
{ 
    "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); 
     } 

하지만 나도 몰라, 난 그 우아한에서 너무 멀리 방법입니다 생각합니다. 더 나은 접근 방법이 있습니까? 감사합니다. . :)

+0

나는 이것이 복제본이라고 확신합니다. 주위를 검색해보십시오. – visc

답변

3

응답에 대한 래퍼 클래스를 만듭니다.

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() 메서드에서 호출하는 것을 고려하고 생성자를 호출 한 후 호출하는 것이 좋습니다.

1

일반적으로 두 번 직렬화 할 필요가 없습니다. 가장 간단한 해결책은 클래스를 만들어 JSON의 가장 바깥 쪽 부분을 표현한 다음 @Alex Wiese's answer에 표시된대로 역 직렬화하는 것입니다.

루트 클래스없이 deserialize하려는 경우 JObject에 직렬화를 해제 한 후에 ToObject<T>() 메서드를 사용할 수 있습니다.

JObject jsonResponse = JsonConvert.DeserializeObject<JObject>(jsonResponseString); 
Countries = jsonResponse["CountriesAndCities"].ToObject<List<Country>>();