C# -迭代动态JSON时遇到问题

4xy9mtcn  于 2023-11-20  发布在  C#
关注(0)|答案(1)|浏览(132)

我试图从一个网站拉JSON数据,我在迭代它返回的对象时遇到了一些麻烦。有人能帮助导航这个结构吗?我对它不统一感到困惑。

using (var httpClient = new HttpClient())
{
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "myToken");
    httpClient.BaseAddress = new Uri("https://app.website.com/data/");

    HttpResponseMessage response = httpClient.GetAsync("getData.json?item=myItem").Result;
    response.EnsureSuccessStatusCode();

    dynamic result = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
    Console.WriteLine("Result: " + result);

    dynamic jsonArray = result.results;
                
    foreach (var item in jsonArray.items)
    {
        Console.WriteLine(item.date1);
    }
}

字符串
下面是我处理的JSON数组。我的目标是遍历item并获得所有的date1date2值。我不需要其他任何东西。

{
    "results": {
        "copyright": "Copyright",
        "items": [{
            "info": {
                "longname": "XXX",
                "shortname": "YYY"
            },
            "item": [{
                "date1": "2022-01-01",
                "date2": "2022-01-05",
            }, {
                "date1": "2022-04-01",
                "date2": "2021-04-07",
            }],
            "key": {
                "keyName": "AAA",
                "keySym": "BBB",
            },
            "symString": "BBB"
        }],
        "count": 1
    }
}

xlpyo6sf

xlpyo6sf1#

使用dynamic会让你自己做额外的工作,因为你会失去智能感知和编译时类型检查。Json.NET为dynamic返回的底层类型通常是JToken的某个子类型,所以完成任务的最简单方法是将其转换为JToken并使用SelectTokens(),如下所示:

var result = JsonConvert.DeserializeObject<JToken>(jsonString);
var dates = result.SelectTokens("results.items[*].item[*]")
    .Select(i => new { date1 = i["date1"].ToObject<DateOnly>(), date2 = i["date2"].ToObject<DateOnly>() });
foreach (var item in dates)
{
    Console.WriteLine($"Date1={item.date1}, Date2={item.date2}.");
}

字符串
哪个指纹

Date1=01/01/2022, Date2=01/05/2022.
Date1=04/01/2022, Date2=04/07/2021.


备注:

演示小提琴here

相关问题