如何在C#中使用这个json变量?

时间:2014-11-14 23:27:00

标签: c# json json.net

我想在json中获取数据并在我的程序中使用它们。我使用这些代码:

public class Test
        {
            public class Coord
            {
                public double lon { get; set; }
                public double lat { get; set; }
            }

            public class Weather
            {
                public int id { get; set; }
                public string main { get; set; }
                public string description { get; set; }
                public string icon { get; set; }
            }

            public class Root
            {
                public Coord coord { get; set; }
                public List<Weather> weather { get; set; }
                public string name { get; set; }
            }
        }

我知道如何使用这样的简单变量:

var obj = JsonConvert.DeserializeObject<Test.Root>(jsontest);
double myLon = obj.coord.lon;

我的问题是如何在天气类中使用变量,因为它在列表中定义了!例如,我想存储&#34; icon&#34;在一个字符串变量中。我是C#的新人,请帮帮我。

1 个答案:

答案 0 :(得分:1)

由于天气属于List'1类型,您必须像使用索引的列表一样访问它:

double icon = obj.weather[0].icon

或使用linq:

double icon = obj.weather.First().icon

您可以在该列表中包含多个Weather个对象,因此请相应地对其进行处理。