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
相关产品推荐
相关产品推荐

