Typescript将json反序列化为具有多种类型的集合 [英] Typescript deserializing json into collection with multiple types
问题描述
我正在为项目使用Typescript,需要将一个集合序列化为json,将其保存到文件中,然后将该文件反序列化为一个类似的集合.该集合看起来像:
I'm using typescript for a project and need to serialize a collection to json, save it to a file and later deserialize that file into a similar collection. The collection looks something like:
elements: Array<tool>
我的工具界面如下:
export interface tool {
name: string;
draw(context:any);
}
和工具实现如下:
export class textTool implements tool {
name: string;
fontSize:number;
fontType:string;
draw(context:any){
// draws the control...
}
}
我有一些工具界面的实现:textTool,imageTool和rectangleTool.我需要解决的问题是,当我将文件内容反序列化为工具集合时,我只会得到一个常规对象,而不是例如textTool的实例.
I have few implementations of tool interface: textTool, imageTool and rectangleTool. The problem I need to solve is that when I deserialize the file content into a collection of tool I get just a regular object and not an instance of textTool for example.
我正在使用JSON.stringify(elements)
创建json,并使用JSON.parse(jsonText)
反序列化.
I'm using JSON.stringify(elements)
to create a json and JSON.parse(jsonText)
to deserialize.
我知道解析器没有办法知道给定json文本没有信息的情况下它应该创建哪种类型的实例.我想添加一个字段或一些东西来标识我需要哪个类实例,然后手动新建"该类.我不需要手动将json解析为工具集合(具有正确类型)的任何选项?
I understand that the parser has no way to know which type it should create an instance of given the json text has no information about it. I thought of adding a field or something to identify which class instance I need and manually 'new' that class. Any options where I don't need to manually parse the json to collection of tool (with proper types)?
推荐答案
正如您所说,您可以添加一个字段type
,在类型字符串与实现类之间创建一个映射,然后转换代码将非常简单:
As you said you can add a field type
, create a mapping between type-string to implementation-class and then conversion code will be pretty straight forward:
export interface tool {
type: string;
name: string;
draw(context:any): void;
}
class textTool implements tool {
type:string = 'textTool';
name:string;
fontSize:number;
fontType:string;
draw(context:any):void {
}
}
const typeMapping:any = {
'textTool' : textTool
//all other types
};
let json = '[{"type":"textTool", "name": "someName", "fontSize": 11}]';
let elements: Array<tool> = JSON.parse(json).map((i:any) => {
let target:any = new typeMapping[i.type];
for (const key in i) {
target[key] = i[key];
}
return target;
});
*克隆代码非常简单,但是对于普通对象来说已经足够了.
* Cloning code is very simplistic, but it is good enough for plain objects.
这篇关于Typescript将json反序列化为具有多种类型的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!