繁体   English   中英

Typescript 类反序列化 json

[英]Typescript classes deserialized json

我有 2 个代表树结构的类,如下所示:

class Node {
        private _id: string;
        name: string;
        parent?: Node;
        children: Node[];
}

class Tree {
    root: Node;
    treeMap: Map<string, Node>;
}

我正在写一个 api GET /tree它应该以下列方式返回树 json:

[
    {
        "1": {
            "name": "root",
            "children": [
                {
                    "2": {
                        "name": "fish",
                        "children": [] // empty children
                    }
                },
                {
                    "3": {
                        "name": "bird",
                        "children": [ ...<any children>... ]
                    }
                }
            ]
        }
    }
]

当我执行ctx.body = tree时,这就是 api 返回的内容:

{
    "root": {
        "_id": "1",
        "name": "root",
        "children": [
            {
                "_id": "2",
                "name": "fish",
                "children": []
            },
            {
                "_id": "3",
                "name": "bird",
                "children": []
            }
        ]
    },
    "treeNodeMap": {}
}

将其转换为所需的 json 格式的正确方法是什么?

让您的类实现toJSON()以生成您想要的数据结构。

// Define the data structure
interface SerialisedNode {
  [id: string]: {
    name: string;
    children: SerialisedNode[]
  }
}

class Node {
  private _id: string;
  name: string;
  parent?: Node;
  children: Node[];

  toJSON(): SerialisedNode {
    return {
      [ this._id ]: {
        name: this.name,
        children: this.children.map(node => node.toJSON())
      }
    }
  }
}

class Tree {
  root: Node;
  treeMap: Map<string, Node>;

  toJSON(): SerialisedNode {
    return this.root.toJSON();
  }
}

当您的Tree (或任何Node )被字符串化为 JSON 时,转换将启动并提供备用数据结构。

TypeScript 游乐场演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM