首页 > 解决方案 > 快速结构识别

问题描述

我想知道一种聪明而有效的方法来区分另一个数据结构。

如果我们假设数据结构以 JSON 树的形式存储在一个数组中,那么问题可以总结如下:

[
    // Type 1
    {
        "name" : "value",
        "key" : "other_value",
    },
    // Type 2
    {
        "name" : "value",
        "key" : "other_value",
        "another_key" : "another_value",
        "data" : [
            { "a" : 1 },
            { "a" : 2 },
            // ...
        ]
    },
    // ...
]

我想出的可能解决方案包括:

  1. 手工制作的硬编码规则,例如if 'another_key' in data,但是当数据条目的数量和不同类型的数量增加时,维护起来会很繁重。
  2. 结构指纹:对除叶子之外的整个树进行散列,并使用散列来识别唯一的数据结构。"data" : [ ... ]如果条目的数量是固定的,这将是一个很好的解决方案。
  3. Schemas ( JSON Schema , XML Schema , ...),但我觉得这对于所讨论的问题来说有点“过度设计”。

您是否知道解决此问题和类似问题的更好方法?


编辑:更多示例

class Book {
    public int id;
    public string title;
}

class BookWithAuthor : Book {
    public string author;
}

class BookWithMultipleAuthors : BookWithAuthor {
    public string[] moreAuthors; // array structure
}

class BookWithSequel : BookWithAuthor {
    public Book sequel; // list structure
}

class BookWithSequelsAndSpinoffs : BookWithAuthor {
    public BookWithAuthor[] sequels;
    public Book[] spinoffs;
    // tree structure
}

想象一下,有一个(损坏的)序列化 aBook[] books没有关于它是什么类型的书并且需要恢复原始格式(或等效的东西)的信息。

另外,为了简单起见,我使用了 C#,这是一个普遍的问题。

标签: data-structuresfingerprinting

解决方案


推荐阅读