反序列化json树结构并设置父级 [英] Deserializing json tree structure and setting parents

查看:218
本文介绍了反序列化json树结构并设置父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个非常基本的问题,但我一直在努力寻找一个优雅的解决方案.我有一个Node类,我正在使用它来构建树形结构.然后使用JsonConvert.SerializeObject(..)将其序列化为JSON.为了防止序列化时进行循环引用,我在属性上放置了JsonIgnore属性.

This seems like a really basic problem, but I'm struggeling to find an elegant solution. I have a Node class that I'm using to build a tree structure. This is then serialized to JSON using JsonConvert.SerializeObject(..). In order to prevent circular references when serializing, I've placed a JsonIgnore attribute on the Parent property.

显然,这意味着父项不会在结果JSON输出中作为每个节点的一部分进行序列化.

This obviously means that the parent is not being serialized as part of each node in the resulting JSON output.

当我反序列化相同的JSON字符串时,我希望为Node对象分配正确的Parent,以便我可以轻松地向上遍历树.最干净,最简单的方法是什么?

When I deserialize the same JSON string, I want the Node objects to have the proper Parent assigned so that I can easily traverse the tree upwards. What is the cleanest and simplest way of achieving this?

[JsonObject]
public class Node : IEnumerable<Node>
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    [JsonIgnore]
    public Node Parent { get; private set; }

    [JsonProperty("Children")]
    private readonly Dictionary<Guid, Node> _children = new Dictionary<Guid, Node>();

    public Node()
    {
        Id = Guid.NewGuid();
    }

    public void Add(Node departmentNode)
    {
        if (node.Parent != null)
        {
            node.Parent._children.Remove(node.Id);
        }

        node.Parent = this;
        _children.Add(node.Id, node);
    }

    public IEnumerator<Node> GetEnumerator()
    {
        return _children.Values.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

推荐答案

您可以完全摆脱父级,并在需要时使用FindParent(node.Id)之类的东西.

You could get rid of the Parent altogether and use something like FindParent(node.Id) when you need to find it.

如果这不可行(应该是这样),并且您需要一个父引用,那么我的建议是在反序列化之后浏览树并设置父引用.

If this not feasible (it should be though) and you need to have a parent reference my suggestion would be to go through the tree and set the parent references after you deserialize.

这篇关于反序列化json树结构并设置父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆