将 JSON 反序列化为具有子对象的 C# 对象

Deserialize JSON to C# Objects with Childs

我有一个 JSON 字符串,我需要一些帮助来反序列化它。 目前我的结果总是空的。

var results = JsonConvert.DeserializeObject<Root>(json);
// result == null

我的JSON:

{"First":{"FirstData1":{"date":"2018-01-01","hint":""},
"FirstData2":{"date":"2018-01-06","hint":""}},
"Second":{"SecondData1":{"date":"2018-01-01","hint":""},
"SecondData2":{"date":"2018-01-06","hint":""}}}....

仅在最后一个节点上有实际的 属性 命名...

我的对象

public class Root
{
    public IEnumerable<TempModelRoot> Value{ get; set; }
}

public class TempModelRoot
{
    [JsonProperty("Key")]
    public string Key { get; set; }

    [JsonProperty("Value")]
    public List<TempModelChild> Value { get; set; }
}

public class TempModelChild
{
    [JsonProperty("Key")]
    public string Key { get; set; }

    [JsonProperty("Value")]
    public TempModelInfo Value { get; set; }
}


public class TempModelInfo
{
    [JsonProperty("date")]
    public string date { get; set; }

    [JsonProperty("hint")]
    public string hint { get; set; }
}

很可能您尝试反序列化的模型与基于 json 本身的实际预期模型不匹配。

解决这个问题的一个简单方法是使用 Quick Types Model Generator(unaffiliated) 等工具,它允许您根据提供的 json 文件。

生成后您可以比较 and/or 用生成的模型替换您的模型。 发现并解决模型的问题。

除了@MX D 的回答之外,我想添加两个更有用的模型生成器站点,它以 JSON 作为输入并给出适当的模型 类.

Json2Csahrp

JsonUtils

使用,每当你发现难以生成复杂模型时类。