将JSON反序列化为带有Childs的C#对象 [英] Deserialize JSON to C# Objects with Childs
问题描述
我有一个JSON字符串,我需要一些帮助来反序列化它. 目前,我的结果始终为空.
I have a JSON string and I need some help to deserialize it. At the moment my result is always null.
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":""}}}....
只有在最后一个节点上才有实际的属性命名...
Only on the last Node there is actual property naming...
MyObjects
MyObjects
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本身的实际预期模型之间不匹配.
Most likely you are having a mismatch between the model you are trying to deserialize to, and the actual expected model based of the json itself.
一种简单的解决方法是使用诸如快速类型模型的工具生成器 (未附加功能),它使您可以基于提供的json文件生成C#模型.
A easy way to resolve this is by using a tool such as Quick Types Model Generator(unafiliated) which allows you to generate C# models based upon a provided json file.
生成后,您可以将模型与生成的模型进行比较和/或替换. 找出并解决模型问题.
After generation you can compare and/or replace your models with the generated models. To spot and resolve the issue with your model.
这篇关于将JSON反序列化为带有Childs的C#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!