如何反序列化含重复id字段的JSON?C#新手技术求助
如何反序列化包含多层同名"id"字段的JSON数据
你需要反序列化包含多层"id"字段的JSON,但当前的C#类写法因重复使用JsonProperty("id")无法正常工作,以下是正确的解决方法:
你的JSON结构
"data": [{ "id": 45, "file_name": "test.pdf", "description": "", "attach_date": "2017-11-23T12:18:18Z", "source": { "id": 62, "source_type": "features" }, "created_by": { "id": 100, "user_type": 0 } }]
错误类定义的问题
不能在同一个类中重复标记[JsonProperty("id")],因为JSON里的"source"是嵌套子对象,它的"id"属于子层级,并非Attachment类的直接属性。
正确的类定义方案
为嵌套的子对象单独定义类,在Attachment类中添加对应类型的属性来映射层级关系:
public class Attachment { [JsonProperty("id")] public int AttachmentId { get; set; } [JsonProperty("file_name")] public string FileName { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("attach_date")] public DateTime AttachDate { get; set; } [JsonProperty("source")] public Source Source { get; set; } [JsonProperty("created_by")] public CreatedBy CreatedBy { get; set; } } public class Source { [JsonProperty("id")] public int SourceId { get; set; } [JsonProperty("source_type")] public string SourceType { get; set; } } public class CreatedBy { [JsonProperty("id")] public int CreatedById { get; set; } [JsonProperty("user_type")] public int UserType { get; set; } }
反序列化示例
使用Newtonsoft.Json进行反序列化时,需要先定义匹配最外层结构的根类:
public class RootObject { [JsonProperty("data")] public List<Attachment> Data { get; set; } }
之后就可以正常解析并获取目标字段:
// 假设jsonString是你从Web请求拿到的完整JSON var root = JsonConvert.DeserializeObject<RootObject>(jsonString); // 获取第一个附件的id和对应Source的id int attachmentId = root.Data[0].AttachmentId; int sourceId = root.Data[0].Source.SourceId;
内容的提问来源于stack exchange,提问作者David Petrovic
相关产品推荐
相关产品推荐

