Deserialize JSON to C# Objects with Childs

瘦欲@ 提交于 2019-12-25 01:34:26

问题


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

My 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

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; }
}

回答1:


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.

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.




回答2:


In addition to @MX D 's answer, I want to add two more useful model generator sites, which takes JSON as an input and gives appropriate model classes.

Json2Csahrp

JsonUtils

Use, whenever you find difficult to generate complex model classes.



来源:https://stackoverflow.com/questions/51517404/deserialize-json-to-c-sharp-objects-with-childs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!