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

使用System.Text.Json从嵌套JSON数组提取值的C#实现

用System.Text.Json提取urlscan.io JSON中的result字段URL

方法一:动态遍历JsonElement(无需实体类)

直接解析JSON字符串,定位到results数组后遍历提取目标URL:

using System;
using System.Text.Json;

class Program
{
    static void Main()
    {
        // 模拟urlscan.io返回的JSON结构
        string json = @"
        {
            ""results"": [
                {
                    ""result"": ""https://example.com/page1""
                },
                {
                    ""result"": ""https://example.com/page2""
                }
            ]
        }";

        // 解析JSON文档
        using JsonDocument doc = JsonDocument.Parse(json);
        JsonElement root = doc.RootElement;

        // 定位results数组并遍历
        if (root.TryGetProperty("results", out JsonElement resultsArray))
        {
            foreach (JsonElement item in resultsArray.EnumerateArray())
            {
                if (item.TryGetProperty("result", out JsonElement resultUrl))
                {
                    Console.WriteLine(resultUrl.GetString());
                }
            }
        }
    }
}

方法二:强类型绑定(更规范)

定义与JSON结构匹配的实体类,通过反序列化直接取值:

using System;
using System.Collections.Generic;
using System.Text.Json;

// 对应JSON结构的实体类
public class UrlScanResponse
{
    public List<ResultItem> Results { get; set; }
}

public class ResultItem
{
    public string Result { get; set; }
}

class Program
{
    static void Main()
    {
        string json = @"
        {
            ""results"": [
                {
                    ""result"": ""https://example.com/page1""
                },
                {
                    ""result"": ""https://example.com/page2""
                }
            ]
        }";

        // 反序列化到实体类
        UrlScanResponse response = JsonSerializer.Deserialize<UrlScanResponse>(json);

        // 遍历提取URL
        foreach (var item in response.Results)
        {
            Console.WriteLine(item.Result);
        }
    }
}

关键提示

  • 使用JsonDocument时必须用using语句自动释放资源,避免内存泄漏
  • 若JSON字段名与实体类属性名不匹配,可添加[JsonPropertyName("字段名")]特性做映射
  • 优先用TryGetProperty方法处理可能缺失的字段,避免抛出异常

内容的提问来源于stack exchange,提问作者Leonardo van de Weteringh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 08:45:39