TypeScript:使用装饰器进行自定义 JSON 序列化

TypeScript : Using decorators for custom JSON serialization

我正在尝试实现 this, and this link 中看到的 TypeScript 装饰器。我得到了我的项目 运行,但在从 Decorator 检索一些值时遇到了问题。

首先是相关的 类 :

SerializeDecorator.ts

let toSerialize = new WeakMap();

// for each target (Class object), add a map of property names
export function serialize(target: any, key: string) {
    console.log("Target = " + target + " / Key = " + key);

    let map = toSerialize.get(target);

    if (!map) {
        map = [];
        toSerialize.set(target, map);
    }

    map.push(key);

    console.log(toSerialize);
}

export function print() {
    console.log(toSerialize);
}

/* not used for now
export function getArray() {
    return toSerialize;
}

export function value(key: string) {
    return this[key];
}
*/

DeviceClass.ts

import * as serializer from "./SerializeDecorator";

export class Device {
    @serializer.serialize
    private deviceid: number;
    private indication: number;
    private serialnumber: number;

    private type: string = "MEMS6";
    private value: string;

    public constructor(id: number = 1, indic: number = 1, serial: number = 200001) {
        this.deviceid = id;
        this.indication = indic;
        this.serialnumber = serial;
    }

    public getDeviceid(): number {
        return this.deviceid;
    }

    public setDeviceid(i: number) {
        this.deviceid = i;
    }

    public getIndication(): number {
        return this.indication;
    }

    public setIndication(i: number) {
        this.indication = i;
    }

    public getSerialnumber(): number {
        return this.serialnumber;
    }

    public setSerialnumber(i: number) {
        this.serialnumber = i;
    }

    public getType(): string {
        return this.type;
    }

    public setType(s: string) {
        this.type = s;
    }

    public getValue(): string {
        return this.value;
    }

    public setValue(s: string) {
        this.value = s;
    }

    public toJSON(): any {
        serializer.print();

        // just to return some value ...
        return {
            "test": "test"
        };
    }
}

我的目标

我想将所有要序列化的属性放在一个(弱)Map 中,由 Decorator 保存。然后,一旦所有属性都已放置在地图中,我想在调用重写的 toJSON 函数时检索 属性 的名称及其值。 (一个 for 循环,在每个 key 上循环以获得所需的 target 并检索 value

我的问题

当我如图所示调用 serializer.print() 时,我希望看到如下内容:

WeakMap : { [Object object] : ["deviceid"] }

但我得到了这个:

WeakMap : {}

我的问题

当然,我想知道我想要达到的目标是否可能。如果可能的话,是什么原因使我的 WeakMap 为空?我对 Decorator 语法不太熟悉(例如没有 class),所以它不是 "really" 对象的事实是否会导致它无法保留引用?

您的代码确实有效,但您被 console.log

误导了

weakmap 的键是不可枚举的,所以它看起来是空的。但是调用 gethas 方法,你会发现情况并非如此。