You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手求助:使用VB.NET和Newtonsoft解析JSON提取图片路径

提取JSON中Subject ID对应的JPEG路径方法

你提到的jobject.SelectToken("subjects.locations")没法直接满足需求,因为subjects是数组,每个subject下的locations也是数组,得逐层遍历才能关联ID和对应的JPEG路径。以下是基于Newtonsoft.Json库的具体实现方案:

基础遍历方式

先获取subjects数组,逐个遍历每个subject,再遍历其locations集合提取JPEG路径:

using Newtonsoft.Json.Linq;

// 假设你的JSON字符串已解析为JObject
JObject jsonObj = JObject.Parse(yourJsonString);

foreach (JObject subject in jsonObj["subjects"])
{
    string subjectId = subject["id"].ToString();
    Console.WriteLine($"Subject ID: {subjectId}");
    
    foreach (JObject location in subject["locations"])
    {
        // 提取"image/jpeg"对应的值
        string jpegUrl = location["image/jpeg"].ToString();
        Console.WriteLine($"  JPEG路径: {jpegUrl}");
    }
}

LINQ简洁写法

如果偏好紧凑代码,可直接用LINQ生成ID与JPEG路径的映射集合:

var subjectJpegMap = jsonObj["subjects"]
    .Select(subject => new
    {
        Id = subject["id"].ToString(),
        JpegUrls = subject["locations"]
            .Select(loc => loc["image/jpeg"].ToString())
            .ToList()
    })
    .ToList();

// 遍历结果
foreach (var item in subjectJpegMap)
{
    Console.WriteLine($"ID: {item.Id}, JPEG路径列表: {string.Join(", ", item.JpegUrls)}");
}

注意事项

  • 确保已引用Newtonsoft.Json NuGet包
  • 若JSON结构可能存在空值,建议添加空判断(比如subject["id"]?.ToString())避免空引用异常

内容的提问来源于stack exchange,提问作者Nor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 02:32:16