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

如何无需构建完整模型反序列化JSON获取字符串值?

问题描述

我需要反序列化JSON以获取quote和author字符串值,但不想构建完整的JSON模型(太耗时)。尝试用Dynamic Object实现,但始终无法获取目标值,以下是示例JSON及测试代码:

示例JSON

{
    "success": {
        "total": 1
    },
    "contents": {
        "quotes": [
            {
                "quote": "Plant your own garden and decorate your own soul, instead of waiting for someone to bring you flowers.",
                "length": "102",
                "author": "Veronica A. Shoffstall",
                "tags": [
                    "flowers",
                    "inspire",
                    "self-help",
                    "soul"
                ],
                "category": "inspire",
                "language": "en",
                "date": "2022-12-22",
                "permalink": "https://theysaidso.com/quote/veronica-a-shoffstall-plant-your-own-garden-and-decorate-your-own-soul-instead-o",
                "id": "LQbKQGxVA2rcH4lIwn6OIweF",
                "background": "https://theysaidso.com/img/qod/qod-inspire.jpg",
                "title": "Inspiring Quote of the day"
            }
        ]
    },
    "baseurl": "https://theysaidso.com",
    "copyright": {
        "year": 2024,
        "url": "https://theysaidso.com"
    }
}

测试代码

try
{
    private static readonly HttpClient _httpClient = new HttpClient();
    // 发起API请求
    var response = _httpClient.GetAsync("https://quotes.rest/qod?language=en").Result;
    response.EnsureSuccessStatusCode();

    // 处理响应内容
    var value11 = response.Content.ReadAsStringAsync().Result;
    var gett = JsonConvert.DeserializeObject<dynamic>(value11);
    var quote= gett.contents.quotes.quote;
    
    return quote;
}
catch (Exception ex)
{
    quote = ex.Message;
    return quote;
}
解决方案

问题出在quotes是一个数组(JSON中用[]包裹),你直接通过gett.contents.quotes.quote访问时跳过了数组索引,导致无法正确取值。

修正Dynamic方式的代码

修改访问路径,添加数组索引(示例中仅一条名言,取第一个元素即可):

try
{
    private static readonly HttpClient _httpClient = new HttpClient();
    var response = _httpClient.GetAsync("https://quotes.rest/qod?language=en").Result;
    response.EnsureSuccessStatusCode();

    var value11 = response.Content.ReadAsStringAsync().Result;
    var gett = JsonConvert.DeserializeObject<dynamic>(value11);
    // 访问数组第一个元素再获取quote和author
    var quote = gett.contents.quotes[0].quote;
    var author = gett.contents.quotes[0].author;
    
    return $"名言:{quote},作者:{author}";
}
catch (Exception ex)
{
    return ex.Message;
}

更稳妥的替代方案:使用JObject

如果不想依赖动态类型,可使用Newtonsoft.Json的JObject直接定位节点,类型更明确,避免潜在的动态类型问题:

try
{
    private static readonly HttpClient _httpClient = new HttpClient();
    var response = _httpClient.GetAsync("https://quotes.rest/qod?language=en").Result;
    response.EnsureSuccessStatusCode();

    var jsonString = response.Content.ReadAsStringAsync().Result;
    var jObject = JObject.Parse(jsonString);
    // 通过JSON路径直接定位取值
    var quote = jObject.SelectToken("contents.quotes[0].quote")?.ToString();
    var author = jObject.SelectToken("contents.quotes[0].author")?.ToString();
    
    return $"名言:{quote},作者:{author}";
}
catch (Exception ex)
{
    return ex.Message;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:15:48