【问题标题】:How to use this json variable in C#?如何在 C# 中使用这个 json 变量?
【发布时间】:2014-11-14 23:26:59
【问题描述】:

我想在 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;

我的问题是如何在天气类中使用变量,因为它在列表中定义!例如,我想将“图标”存储在字符串变量中。我是 C# 新手,请帮帮我。

【问题讨论】:

  • 它也应该反序列化任何适用的Weather 对象。它没有这样做吗?
  • 我不清楚你在问什么。您面临的问题是什么?
  • 正如我所说的 double myLon = obj.coord.lon;工作正常但是当我写 string myDescription = obj.weather.description;它不起作用,我的程序出现错误。
  • 你必须像列表一样使用它;如答案。

标签: c# json json.net


【解决方案1】:

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

double icon = obj.weather[0].icon

或使用 linq:

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

您可以在该列表中拥有多个 Weather 对象,因此请相应地对待它。

【讨论】:

  • 尤其是第二个,你应该使用FirstOrDefault,以防列表为空(除非你可以捕捉到异常)。
  • FirstOrDefault().icon 如果列表为空,仍会抛出 NullReferenceException。重点是,除非您知道自己在做什么,否则不要使用 linq。
  • 啊;好点。 JSON 不太可能有 empty 列表,它只是 null。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2013-05-02
  • 1970-01-01
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
相关资源
最近更新 更多