将 JSON 转换为 C# 复杂对象

Convert JSON to C# complex object

我在 C# 中有这个结构,我想创建可以成功转换成它的 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; }
}

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

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

但我在树中仍然得到空值;更不用说 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.'

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

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

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

为此 json 您需要创建一个包装器 class。

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 个对象 属性 "Tree"

这又有一个 属性 "Root"

其中包含多个属性