在json中反序列化嵌套列表的最佳方法 - C#

时间:2017-12-18 22:45:13

标签: c# json json.net

我得到了这个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);
        }

但我不知道,我认为这离优雅太远了。 有没有更好的方法呢? 谢谢。 :)

2 个答案:

答案 0 :(得分:4)

为响应创建一个包装类。

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 :(得分:3)

一般来说,您永远不需要反序列化两次。最简单的解决方案是创建一个类来表示JSON的最外层部分,然后反序列化为@Alex Wiese's answer中显示的那个。

如果要在没有根类的情况下反序列化,则可以在将<html><body><div><h2>Hi All</h2><hr></div></body></html> NOTICE TO RECIPIENT: If you are not the intended recipient of this e-mail, you are prohibited from sharing, copying, or otherwise using or disclosing its contents. If you have received this e-mail in error, please notify the sender immediately by reply e-mail and permanently delete this e-mail and any attachments without reading, forwarding or saving them. Thank you. 反序列化后使用ToObject<T>()方法。

JObject