json 打字稿对象序列化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16261119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:42:50  来源:igfitidea点击:

Typescript objects serialization?

javascriptjsonserializationtypescript

提问by Nik

Are there any means for JSON serialization/deserialization of Typescript objects so that they don't loose type information? Simple JSON.parse(JSON.stringify)has too many caveats.

是否有任何方法可以对 Typescript 对象进行 JSON 序列化/反序列化,以便它们不会丢失类型信息?简单JSON.parse(JSON.stringify)有太多的警告。

Or I should use adhoc solutions?

或者我应该使用临时解决方案?

回答by basarat

Use Interfaces to get strong types:

使用接口获得强类型:

// Creating 
var foo:any = {};
foo.x = 3;
foo.y='123';

var jsonString = JSON.stringify(foo);
alert(jsonString);


// Reading
interface Bar{
    x:number;
    y?:string; 
}

var baz:Bar = JSON.parse(jsonString);
alert(baz.y);

And use type assertion "<>" if you need to.

如果需要,请使用类型断言“<>”。

回答by AQuirky

I think a better way to handle this is to use Object.assign (which however requires ECMAScript 2015).

我认为处理这个问题的更好方法是使用 Object.assign(但这需要 ECMAScript 2015)。

Given a class

给定一个班级

class Pet {
    name: string;
    age: number;
    constructor(name?: string, age?: number) {
        this.name = name;
        this.age = age;
    }
    getDescription(): string {
        return "My pet " + this.name + " is " + this.age + " years old.";
    }
    static fromJSON(d: Object): Pet {
        return Object.assign(new Pet(), d);
    }
}

Serialize and deserialize like this...

像这样序列化和反序列化......

var p0 = new Pet("Fido", 5);
var s = JSON.stringify(p0);
var p1 = Pet.fromJSON(JSON.parse(s));
console.log(p1.getDescription());

To take this example to the next level, consider nested objects...

要将这个例子提升到一个新的水平,考虑嵌套对象......

class Type {
    kind: string;
    breed: string;
    constructor(kind?: string, breed?: string) {
        this.kind = kind;
        this.breed = breed;
    }
    static fromJSON(d: Object) {
        return Object.assign(new Type(), d);
    }
}
class Pet {
    name: string;
    age: number;
    type: Type;
    constructor(name?: string, age?: number) {
        this.name = name;
        this.age = age;
    }
    getDescription(): string {
        return "My pet " + this.name + " is " + this.age + " years old.";
    }
    getFullDescription(): string {
        return "My " + this.type.kind + ", a " + this.type.breed + ", is " + this.age + " years old.";
    }
    static fromJSON(d: Object): Pet {
        var o = Object.assign(new Pet(), d);
        o.type = Type.fromJSON(o['type']);
        return o;
    }
}

Serialize and deserialize like this...

像这样序列化和反序列化......

var q0 = new Pet("Fido", 5);
q0.type = new Type("dog", "Pomeranian");
var t = JSON.stringify(q0);
var q1 = Pet.fromJSON(JSON.parse(t));
console.log(q1.getFullDescription());

So unlike using an interface, this approach preserves methods.

因此,与使用接口不同,这种方法保留了方法。

回答by nexiss

The AQuirky answerworks for me. You may have some troubles with the Object.assign method. I had to modify my tsconfig.json to include:

AQuirky答案对我来说有效。您可能在使用 Object.assign 方法时遇到一些麻烦。我不得不修改我的 tsconfig.json 以包括:

"compilerOptions": {
    ...
    "lib": ["es2015"],
    ...
}

回答by Yhan

I think the better way is to use this library. It makes it easier to serialize/deserialize object/json.

我认为更好的方法是使用这个库。它可以更轻松地序列化/反序列化 object/json。

https://www.npmjs.com/package/@peerlancers/json-serialization

https://www.npmjs.com/package/@peerlancers/json-serialization