【发布时间】:2012-11-29 20:20:52
【问题描述】:
我正在尝试反序列化从 LinkedIn Javascript API 获取的 Json 对象:
{"_key":"~","educations":{"_total":2,"values":[{"degree":"Bachelor of Science (BSc)","endDate":{"year":2004},
"fieldOfStudy":"Computer Software Engineering","id":134450447,"schoolName":"Bristol University","
startDate":{"year":2009}},{"id":143651018,"schoolName":"University of Kingston"}]},"emailAddress":
"test@test.com","firstName":"Robert","lastName":"Matthews"}
我编写了一个自定义类来存储这些值并使用 Json.NET 反序列化它们:
[Serializable]
public class LinkedInUserData {
[JsonProperty(PropertyName = "emailAddress")]
public string EmailAddress { get; set; }
// other properties cut out for simplicity
[JsonProperty(PropertyName = "educations")]
public Educations Educations { get; set; }
}
[Serializable]
public class Educations {
[JsonProperty(PropertyName = "_total")]
public string Total { get; set; }
[JsonProperty(PropertyName = "values")]
public Values Values { get; set; }
}
[Serializable]
public class Values { // cut down for simplicity
[JsonProperty(PropertyName = "degree")]
public string Degree { get; set; }
}
LinkedInUserData linkedData = JsonConvert.DeserializeObject<LinkedInUserData>(profile);
我能够毫无问题地转换单个对象(无数组等),但我卡在 Educations 中的 Values 对象上,并显示以下错误消息:
无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'Data.Values' 因为该类型需要 JSON 对象(例如 {"name":"value"}) 正确反序列化。要修复此错误 将 JSON 更改为 JSON 对象(例如 {"name":"value"})或更改 将类型反序列化为数组或实现集合的类型 接口(例如 ICollection、IList),例如 List 可以 从 JSON 数组反序列化。也可以添加 JsonArrayAttribute 强制它从 JSON 数组反序列化的类型。小路 'educations.values',第 1 行,第 47 位。
我尝试将 Educations 中的 Values 对象更改为字符串数组,但没有成功。有什么方法可以成功地将 Json 中的值反序列化到我的自定义类中,还是只能按照字符串数组的方式获得一些东西?
编辑 - 列出(值)产品出现以下错误:
读取字符串时出错。意外标记:StartObject。小路 'educations.values[0].endDate',第 1 行,第 96 位。
编辑 2 - 好的,我现在明白了,List (of values) 确实有效,然后它在 StartDate 和 EndDate 上跳闸,因为它们本身就是对象,我设置了这两个作为strings。我很难理解Json 字符串,但Link2CSharp 帮助我解决了它。
【问题讨论】:
-
您是否尝试过将 preperty
Values的类型更改为List<Values>或Values[]? -
我很确定我已经尝试过 PLB,但无论如何我都会仔细检查!
标签: c# json.net deserialization linkedin