将JSON转换为C#复杂对象

时间:2019-10-21 11:26:45

标签: c# json object tree json-deserialization

我在C#中具有此结构,我想创建可以成功转换为JSON的JSON,以便可以轻松地在JS逻辑中找到我的错误。

public class Tree
{
        public Root Root { get; set; }
        public Tree()
        {}
}

public class Root : Node
{
        public Root(int _id, int _fk, string _name, string _code, List<Node> _children, List<Item> _leaves)
            : base(_id, _fk, _name, _code, _children, _leaves)
        {
        }

        public Root()
        { }
}

public abstract class Node
{
        public int? ID { get; set; }
        public int? FK { get; set; }
        public string Name { get; set; }
        public string Code { get; set; }
        public List<Node> children { get; set; }
        public List<Item> leaves { get; set; }

        public Node(int? _id, int? _fk, string _name, string _code, List<Node> _children, List<Item> _leaves)
        {
            ID = _id;
            FK = _fk;
            Name = _name;
            Code = _code;
            children = _children;
            leaves = _leaves;
        }
        public Node ()
        {}
}

public class Item
{
        public string Code { get; set; }
        public string Desc { get; set; }
        public string Uom { get; set; }
        public float? Measurements { get; set; }
        public int? FK { get; set; }
        public int? Tier { get; set; }
        public bool IsADPresent { get; set; }
}

我试图输入命令JsonConvert.DeserializeObject<Tree>(tree)的最基本的JSON是:

{
    "Tree": {
        "Root": {
            "children": [],
            "leaves": [],
            "FK": 1,
            "ID": 1,
            "Name": " LOGISTICS",
            "Code": "PT01"
        }
    }
}

但是在Tree中我仍然为空;更不用说当JSON变得毛茸茸的时候(树最多可以拥有第5个孙代)。

谢谢

更新:从JSON移除Tree时,出现异常: Newtonsoft.Json.JsonSerializationException: 'Could not create an instance of type StatusUpdater.Models.NPoco.Node. Type is an interface or abstract class and cannot be instantiated. Path 'Root.children[0].children', line 1, position 33.'

2 个答案:

答案 0 :(得分:3)

您应该从JSON中删除Tree,因为Tree是目标类型,不需要包含在JSON中。

{
    "Root": {
        "children": [],
        "leaves": [],
        "FK": 1,
        "ID": 1,
        "Name": " LOGISTICS",
        "Code": "PT01"
    }
}

EDIT:为了反序列化抽象Node元素,您将需要一个具体的类型和一个自定义转换器。查看Deserializing a collection of abstract classes和列出的所有重复链接

答案 1 :(得分:1)

对于此json,您将需要创建包装器类。

public class X { public Tree {get; set;} } 

(...)

var tree = JsonConvert.DeserializeObject<X>(tree)?.Tree;


为什么?

让我们检查一下json。

{
    "Tree": {
        "Root": {
            "children": [],
            "leaves": [],
            "FK": 1,
            "ID": 1,
            "Name": " LOGISTICS",
            "Code": "PT01"
        }
    }
}

此json包含

1个对象具有属性“树”

,而该属性又具有一个“根”属性

包含多个属性