我从对REST服务器的AJAX调用中接收到一个JSON对象。这个对象的属性名与我的TypeScript类相匹配(这是这个问题的后续)。
初始化它的最佳方法是什么?我不认为这将工作,因为类(& JSON对象)的成员是对象的列表和成员是类,而这些类的成员是列表和/或类。
但我更喜欢一种方法,查找成员名和分配他们,创建列表和实例化类的需要,所以我不必为每个类中的每个成员写显式代码(有很多!)
我从对REST服务器的AJAX调用中接收到一个JSON对象。这个对象的属性名与我的TypeScript类相匹配(这是这个问题的后续)。
初始化它的最佳方法是什么?我不认为这将工作,因为类(& JSON对象)的成员是对象的列表和成员是类,而这些类的成员是列表和/或类。
但我更喜欢一种方法,查找成员名和分配他们,创建列表和实例化类的需要,所以我不必为每个类中的每个成员写显式代码(有很多!)
当前回答
对于简单的对象,我喜欢这个方法:
class Person {
constructor(
public id: String,
public name: String,
public title: String) {};
static deserialize(input:any): Person {
return new Person(input.id, input.name, input.title);
}
}
var person = Person.deserialize({id: 'P123', name: 'Bob', title: 'Mr'});
利用在构造函数中定义属性的能力可以使其简洁。
这将为您提供一个类型化对象(与所有使用object的答案相比)。赋值或一些变量,给你一个对象),不需要外部库或装饰器。
其他回答
我一直在用这个家伙来做这项工作:https://github.com/weichx/cerialize
它非常简单,但功能强大。它支持:
整个对象树的序列化和反序列化。 同一对象上的持久和瞬态属性。 用于自定义(反)序列化逻辑的钩子。 它可以(反)序列化到一个现有的实例中(这对Angular来说很棒),也可以生成新的实例。 等。
例子:
class Tree {
@deserialize public species : string;
@deserializeAs(Leaf) public leafs : Array<Leaf>; //arrays do not need extra specifications, just a type.
@deserializeAs(Bark, 'barkType') public bark : Bark; //using custom type and custom key name
@deserializeIndexable(Leaf) public leafMap : {[idx : string] : Leaf}; //use an object as a map
}
class Leaf {
@deserialize public color : string;
@deserialize public blooming : boolean;
@deserializeAs(Date) public bloomedAt : Date;
}
class Bark {
@deserialize roughness : number;
}
var json = {
species: 'Oak',
barkType: { roughness: 1 },
leafs: [ {color: 'red', blooming: false, bloomedAt: 'Mon Dec 07 2015 11:48:20 GMT-0500 (EST)' } ],
leafMap: { type1: { some leaf data }, type2: { some leaf data } }
}
var tree: Tree = Deserialize(json, Tree);
你可以像下面这样做
export interface Instance {
id?:string;
name?:string;
type:string;
}
and
var instance: Instance = <Instance>({
id: null,
name: '',
type: ''
});
我已经创建了一个生成TypeScript接口和运行时“类型映射”的工具,用于对JSON的结果执行运行时类型检查。解析:ts.quicktype.io
例如,给定这个JSON:
{
"name": "David",
"pets": [
{
"name": "Smoochie",
"species": "rhino"
}
]
}
quicktype生成以下TypeScript接口和类型映射:
export interface Person {
name: string;
pets: Pet[];
}
export interface Pet {
name: string;
species: string;
}
const typeMap: any = {
Person: {
name: "string",
pets: array(object("Pet")),
},
Pet: {
name: "string",
species: "string",
},
};
然后检查JSON的结果。根据类型映射解析:
export function fromJson(json: string): Person {
return cast(JSON.parse(json), object("Person"));
}
我省略了一些代码,但您可以尝试快速输入细节。
上面描述的第4个选项是一种简单而漂亮的方法,它必须与第二个选项相结合,在这种情况下,您必须处理一个类层次结构,例如成员列表,它是成员超类的任何一个子类,例如Director extends member或Student extends member。在这种情况下,你必须以json格式给出子类类型
也许不现实,但简单的解决方案:
interface Bar{
x:number;
y?:string;
}
var baz:Bar = JSON.parse(jsonString);
alert(baz.y);
对困难的依赖也要努力!!