【问题标题】:How to iterate thorugh JArray items in list如何遍历列表中的数组项
【发布时间】:2016-09-21 20:10:06
【问题描述】:

这是我的 json 数据:

{
    "date": "2016-08-26",
    "time_of_day": "14:19",
    "request_time": "2016-08-26T14:19:59+01:00",
    "station_name": "Derby",
    "station_code": "DBY",
    "departures": {
      "all": [
        {   
           "service": "22152000",
        },
        {
           "service": "22150000",
        },
        {
           "service": "22180008",
        }
      ]
    }
}

我要做的是将上面 json 中的每个服务变量放入一个列表中。在此之后,我想通过 api 链接分别调用这些服务变量中的每一个。这是我的 C# 代码:

JArray items = new JArray();
items.Add(service["service"]);
int serviceLength = items.Count;

for (int i = 0; i < items.Count; i++)
{
    string moreJson = get_web_content("http://transportapi.com/v3/uk/train/service/" + items[i] + "/" + date + "/" + hours + ":" + minutes + "/timetable.json?" + appID + "/" + appKey);

    dynamic schedluedContent = JsonConvert.DeserializeObject(moreJson);
    JArray items2 = new JArray();

    foreach (JObject stops in schedluedContent.stops)
    {

        dr = dt.NewRow();
        dr["Station Code"] = stops["station_code"];
        dr["Station Name"] = stops["station_name"];
        dr["Aimed Arrival Time"] = stops["aimed_arrival_time"];

        dt.Rows.Add(dr);
        GridViewTrainTimes.DataSource = dt;
        GridViewTrainTimes.DataBind();
    }
}

感谢您的帮助!

【问题讨论】:

  • 如果您将 json 转换为模型 json2csharp.com,您可以轻松完成
  • 我不知道从哪里开始,但我会调查一下谢谢!
  • 您尝试执行的操作似乎与数据不匹配。在您的源 json 中没有提及 aimed_arrival_timestopstops 应该是离开吗?
  • @Ceilingfish - 我认为显示的 JSON 代表一个更大的 json 对象中的单个条目,看起来像 { "stops": [ { ... the object in the question ...} ] }

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


【解决方案1】:

您可以使用SelectTokens() 查找所有服务值。 SelectTokens() 支持使用JSONPath syntax 使用通配符和/或过滤器查询嵌套在 JSON 对象深处的多个属性。

var services = stops
    .SelectTokens("departures.all[*].service")
    .Select(t => (string)t)
    .ToList();

这里的[*] 是通配符运算符,返回departures.all[] 数组中的所有条目。

有关 JSONPath 的完整描述,请参阅 here

示例fiddle

【讨论】:

    猜你喜欢
    • 2015-07-29
    • 2018-05-06
    • 1970-01-01
    • 2019-11-16
    • 2016-03-08
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多