【问题标题】:How to iterate through a list to produce variables from deserialized JSON C# ASP.NET如何遍历列表以从反序列化的 JSON C# ASP.NET 生成变量
【发布时间】:2016-04-07 22:45:55
【问题描述】:

这是我的 JSON。我试图从我反序列化的这个 JSON 中将 3 个站代码转换为 3 个单独的变量。

"stations": [
{
  "station_code": "HWV",
  "atcocode": null,
  "tiploc_code": "HTRWTM5",
  "name": "Heathrow Airport   Terminal 5",
  "mode": "train",
  "longitude": -0.490589,
  "latitude": 51.470051,
  "distance": 369
},
{
  "station_code": "HXX",
  "atcocode": null,
  "tiploc_code": "HTRWAPT",
  "name": "Heathrow Airport   Central Terminal Area (T123)",
  "mode": "train",
  "longitude": -0.454333,
  "latitude": 51.471404,
  "distance": 2309
},
{
  "station_code": "HAF",
  "atcocode": null,
  "tiploc_code": "HTRWTM4",
  "name": "Heathrow Airport   Terminal 4",
  "mode": "train",
  "longitude": -0.445463,
  "latitude": 51.458266,
  "distance": 3336
}

这是我的 C#,我首先为站代码创建了一个类,然后反序列化 JSON,并尝试制作一个站代码列表,然后遍历它们以生成 3 个单独的站代码变量。

public class Station
{
    public string station_code { get; set; }
}

JObject json = JObject.Parse(localJson);

            IList<JToken> results = json["stations"].Children().ToList();

            IList<Station> stationResults = new List<Station>();
            foreach (JToken result in results)
            {
                Station stationResult = JsonConvert.DeserializeObject<Station>(result.ToString());
                stationResults.Add(stationResult);
                var station1 = stationResults[0];
                var station2 = stationResults[0];
                var station3 = stationResults[0];
            }

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 你有什么问题?
  • 我试图从 JSON 中为每个 station_code 生成 3 个不同的变量

标签: c# asp.net json json.net


【解决方案1】:

将您的 foreach 更改为:

foreach (JToken result in results)
{
    // This gives you the current station object from the JToken
    Station stationResult = result.ToObject<Station>();

    // Add to your Station list  
    stationResults.Add(stationResult);
}

这将为您提供stationResults 列表中的 3 个Station。您可以使用列表索引(例如stationResults[0])访问列表中的每个电台,或遍历您的列表。

我不明白为什么要将列表中的每个项目分配给单个变量。但如果你真的想要,你可以这样做:

Station station1 = stationResults[0];
Station station2 = stationResults[1];
Station station3 = stationResults[2];

【讨论】:

  • 从 3 个独立的火车站我将获取车站代码放入另一个 api 链接,然后显示每个火车站的时间表
  • 您可以使用stationResults[0].station_code等方式访问station_code。无需将结果列表中的站分配给单个变量。
【解决方案2】:

您可以将localJson 直接反序列化为IList&lt;Station&gt;,因为它是一个数组类型。无需在 foreach 循环中反序列化每一个。

var stations = JsonConvert.DeserializeObject<IList<Station>>(localJson);
var station1 = stations[0].station_code;
var station2 = stations[1].station_code;
var station3 = stations[2].station_code;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2018-03-08
    • 2015-08-07
    相关资源
    最近更新 更多