程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Deserialize nested JSON into C# objects大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Deserialize nested JSON into C# objects?

开发过程中遇到Deserialize nested JSON into C# objects的问题如何解决?下面主要结合日常开发的经验,给出你关于Deserialize nested JSON into C# objects的解决方法建议,希望对你解决Deserialize nested JSON into C# objects有所启发或帮助;

For "Items" use a Dictionary<String, List<Info>>, i.e.:

class Response
{
    public Dictionary<String, List<Info>> Items { get; set; }
    public String[] Errors { get; set; }
}

class Info
{
    public String Prop1 { get; set; }
    public String Prop2 { get; set; }
    public int Prop3 { get; set; }
    public bool Prop4 { get; set; }
}

This assumes that the item names "Item322A" and "Item2B" will vary from response to response, and reads these names in as the Dictionary keys.

Sample fiddle.

解决方法

I am getTing JSON BACk from an API that looks like this:

{
  "Items": {
    "Item322A": [{
      "prop1": "String","prop2": "String","prop3": 1,"prop4": false
    },{
      "prop1": "String","prop3": 0,"prop4": false
    }],"Item2B": [{
      "prop1": "String","prop3": 14,"prop4": true
    }]
  },"Errors": ["String"]
}

I have tried a few approaches to represent this JSON in c# objects (too many
to list herE). I’ve tried with lists and Dictionaries,here is a recent
example of how I’ve tried to represent it:

    private class Response
    {
        public Item Items { get; set; }
        public String[] Errors { get; set; }
    }

    private class Item
    {
        public List<SubItem> SubItems { get; set; }
    }

    private class SubItem
    {
        public List<Info> Infos { get; set; }
    }

    private class Info
    {
        public String Prop1 { get; set; }
        public String Prop2 { get; set; }
        public int Prop3 { get; set; }
        public bool Prop4 { get; set; }
    }

And here is the method I am using to deserialize the JSON:

    using (var sr = new StringReader(responseJSON))
    using (var jr = new JsontextReader(sr))
    {
        var serial = new Jsonserializer();
        serial.FormatTing = FormatTing.Indented;
        var obj = serial.Deserialize<Response>(jr);
    }

obj contains Items and Errors. And Items contains SubItems,but
SubItems is null. So nothing except for Errors is actually getTing
deserialized.

It should be simple,but for some reason I can’t figure out the correct object
representation

大佬总结

以上是大佬教程为你收集整理的Deserialize nested JSON into C# objects全部内容,希望文章能够帮你解决Deserialize nested JSON into C# objects所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:nestedobjects