gpt4 book ai didi

javascript - 将 JSON 对象反序列化为其原始类

转载 作者:搜寻专家 更新时间:2023-10-30 21:55:45 25 4
gpt4 key购买 nike

我正在尝试序列化/反序列化一个对象。我认为最好的方法是将路径保存到作为 json 一部分调用的文件,但我不确定如何获取所述路径。

可以在父级 (Base.ts) 中调用时获取文件 (A.ts/B.ts) 的路径>)?

是否有更好的方法来做到这一点?我正在尝试获取在主 Node 进程中创建的类,并将其传递给工作进程,我能看到的唯一这样做的原因是以某种方式序列化/反序列化该类。

// src/Base.ts
export abstract class Base {

public serialize() {
return JSON.stringify({path: '', obj: this})
}

public static deserialize(json: string) {
let { path, obj } = JSON.parse(json) as { path: string, obj: { [key: string]: any } }

let newable = require(path)
let o = new newable
return Object.assign(o, obj)
}

}

// src/filter/A.ts
export class A extends Base {
public cat: string = 'meow'
public sayHi() { return this.cat }
}

// src/filter/B.ts
export class B extends Base {
public dog: string = 'woof'
public sayHi() { return this.dog }
}

// test.ts
let serializedA = new A().serialize()
let serializedB = new B().serialize()
// Create child...
let worker = cp.fork(path.join(__dirname, './worker'), [], { silent: true })
worker.send({ serializedA, serializedB })

// worker.ts
process.on('message', msg => {
let classA = Base.deserialize(msg.serializedA)
let classB = Base.deserialize(msg.serializedB)
})

最佳答案

想到的最简单的方法是拥有一组与需要适当类的回调关联的类名。

// src/JsonIO.ts
export class JsonIO {

private _classes: { name: string, callback: () => { new(): any } }[] = []

public serialize(obj: any): string {
return JSON.stringify({ class: obj.constructor.name, value: obj })
}

public deserialize(json: string) {
const obj = JSON.parse(json) as { class: string, value: any }
const clazz = this._classes.find(c => c.name == obj.class)
if(!clazz) return obj.value
return Object.assign(new (clazz.callback()), obj.value)
}

public registerClass(name: string, callback: () => { new(): any }) {
this._classes.push({ name, callback })
}

}

// src/Base.ts
export abstract class Base { /* ... */ }

// src/filter/A.ts
export class A {
public cat: string = 'meow'
}

// src/filter/B.ts
export class B {
public dog: string = 'woof'
}

// test.ts
const io = new JsonIO()
io.registerClass('A', () => A /* require('filter/A.ts') */)
io.registerClass('B', () => B /* require('filter/B.ts') */)

const serializedA = io.serialize(new A)
const serializedB = io.serialize(new B)

const a = io.deserialize(serializedA)
const b = io.deserialize(serializedB)

关于javascript - 将 JSON 对象反序列化为其原始类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56814782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com