【发布时间】:2014-11-25 13:51:57
【问题描述】:
我正在使用 JSON.Net 反序列化 JSON 字符串。 JSON字符串是
string testJson = @"{
""Fruits"": {
""Apple"": {
""color"": ""red"",
""size"": ""round""
},
""Orange"": {
""Properties"": {
""color"": ""red"",
""size"": ""round""
}
}
}
}";
我的代码是
public class Fruits
{
public Apple apple { get; set; }
public Orange orange { get; set; }
}
public class Apple
{
public string color { get; set; }
public string size { get; set; }
}
public class Orange
{
public Properties properties { get; set; }
}
public class Properties
{
public string color { get; set; }
public string size { get; set; }
}
我正在尝试使用以下代码对其进行反序列化
Fruits result = JsonConvert.DeserializeObject<Fruits>(testJson);
我的 结果 有一个问题,即 Fruits 与 Apple 和 Orange 有 null 而不是它们的属性、颜色、尺寸。
【问题讨论】:
-
问题是最外面的
{ ... }括号对应你的Fruits类型,而Fruits不包含名为Fruits的属性。尝试创建一个包含Fruits属性的容器类型,然后对其进行反序列化。 -
或者另辟蹊径,将某些内容序列化为 JSON 以了解正确的格式。
标签: c# json json.net deserialization