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

C#解析JSON时如何访问嵌套子对象profile_image.small?

解决无法访问JSON中profile_image.small字段的问题

嘿,你踩了一个JSON嵌套层级的小坑!咱们先把问题根源理清楚:

问题出在哪?

看你提供的JSON结构,profile_image根本不是直接挂在results的条目下面,它是藏在user对象里的!你的代码直接写itemx.profile_image,自然找不到这个字段——正确的访问路径应该是:results条目 → user → profile_image → small。

修正后的Dynamic代码

只需要调整一下访问层级就行,改完的代码是这样:

dynamic array = JsonConvert.DeserializeObject(response);
foreach (var itemx in array["results"]) {
    // 先拿到user对象,再去取profile_image里的small
    MessageBox.Show(itemx.user.profile_image.small.ToString());
}

更靠谱的强类型方案

用dynamic虽然快捷,但很容易犯这种层级错误,而且编译期没法提前检查问题。我更推荐你用强类型序列化,提前定义好对应的数据类,这样代码更安全还能获得智能提示:

先根据JSON结构定义实体类(只保留你需要的关键字段即可):

public class PhotoResponse
{
    public List<Photo> results { get; set; }
}

public class Photo
{
    public User user { get; set; }
}

public class User
{
    public ProfileImage profile_image { get; set; }
}

public class ProfileImage
{
    public string small { get; set; }
}

然后反序列化并访问字段:

var photoResponse = JsonConvert.DeserializeObject<PhotoResponse>(response);
foreach (var photo in photoResponse.results)
{
    MessageBox.Show(photo.user.profile_image.small);
}

这样以后再改代码或者扩展字段的时候,不容易出错,维护起来也更方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:05:54