C#从反序列化的JSON对象中的Array获取值

时间:2018-04-05 13:55:59

标签: c# json foreach

我有一个JsonObject我反序列化以使用我从api获得的数据。 不知怎的,我似乎无法弄清楚如何从我回来的数组中获取数据,尽管我可以读取布尔“ok”返回的内容。 我试图将数组放在foreach循环中以检索所有名称,但没有成功,因为我不

{
    "ok": true,
    "establishments": [
        {
            "id": "d2sd2-axsd7gjd2-g3sdasd",
            "name": "Hops n Beers",
            "address": ":HopeStreet",
            "lat": : 54.595112,
            "lng": : -5.935926,
        },
                {
            "id": "z1ty4-axst7jjd2-g3spocd",
            "name": "Good ol Bakery",
            "address": ":Bakerstreet",
            "lat": : 54.54312,
            "lng": : -5.11926,
        },
    ]
}

^这就是api返回的内容

我现在的目标是通过foreach循环获取企业的名称。 我的代码(删除了循环,在尝试各种各样的事情后变得混乱):

var deserializedLocList = JsonConvert.DeserializeObject<IDictionary<string, object>>(await response.Content.ReadAsStringAsync());
if ((bool)deserializedLocList["ok"])
{
    //I do get a true back, but here I want to create a foreach loop to get all the names
    await DisplayAlert("Succes", "HOORAY!", "OK");
}
else
{
    await DisplayAlert("Fout", (string)deserializedLocList["reason"], "OK");
}

我还创建了一个我在尝试某些事情时使用的类,而不是使用Dictionary创建List。

班级:

[JsonObject(MemberSerialization.OptIn)]
public class LocationListResults
{
    [JsonProperty("establishments")]
    public Establishment Establishments { get; set; }
}
public class Establishment
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("address")]
    public string  Address{ get; set; }
    [JsonProperty("lat")]
    public string Lat{ get; set; }
    [JsonProperty("lng")]
    public string Lng { get; set; }
}

1 个答案:

答案 0 :(得分:3)

最佳的最佳解决方案是创建一个Class,表示您正在接收的对象,并将内容反序列化为该类型。

你几乎就在那个班级,你只需要说它的名单是一个企业名单

[JsonObject(MemberSerialization.OptIn)]
public class LocationListResults
{
    [JsonProperty("ok")]
    public Boolean OK { get; set; }
    [JsonProperty("establishments")]
    public List<Establishment> Establishments { get; set; }
}
public class Establishment
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("address")]
    public string  Address{ get; set; }
    [JsonProperty("lat")]
    public string Lat{ get; set; }
    [JsonProperty("lng")]
    public string Lng { get; set; }
}


var deserializedLocList = JsonConvert.DeserializeObject<LocationListResults>(await response.Content.ReadAsStringAsync());
if (/* access here the boolean 'okay' from deserializedLocList or whatever you require */)
{
    //I do get a true back, but here I want to create a foreach loop to get all the names
    await DisplayAlert("Succes", "HOORAY!", "OK");
}
else
{
    await DisplayAlert("Fout", /* access here the value from deserializedLocList or whatever you need */, "OK");
}