英文:
How can I cast a JSON object to a TypeScript class instance without any external library?
问题
我正在尝试将一个JSON对象进行类型转换,示例如下:
class Person {
constructor(
public firstName,
public lastName
) {}
function getName() {
return this.firstName + “ “ + this.lastName;
}
}
目标是解析如下所示的JSON:
{
firstName: “Max“,
lastName: “Mustermann“
}
以便将其转换为上述类的实例,以访问所有属性和方法。
是否有一种简单的方法可以创建一个函数,使这种类型的JSON和类的转换功能成为可能?
同时,嵌套对象也应该是可能的。
我可以为每个不同的类编写一个工厂方法,但应该有一种更好的方法来获得这样的功能。
英文:
I am trying to cast a JSON object like the following example:
class Person {
constructor(
public firstName,
public lastName
) {}
function getName() {
return this.firstName + “ “ + this.lastName;
}
}
The goal is to parse the JSON which looks like this:
{
firstName: “Max“,
lastName: “Mustermann“
}
to an instance of the above class to access all properties and methods.
Is there an easy way to create a function which can make such a functionality possible for such type of JSONs/classes?
Also nested objects should be possible.
I can write a factory method for every different class but there should be an better way to get such functionality.
答案1
得分: 1
创建你的类如下,注意构造函数:
class Person {
public firstName: string;
public lastName: string;
public constructor(init?: Partial<Person>) {
Object.assign(this, init);
}
function getName() {
return this.firstName + " " + this.lastName;
}
}
将 JSON 传递给这个构造函数:
let person = new Person({ firstName: "A", lastName: "B" });
console.log(person);
英文:
Use Object.assign
Create your class like this, observe the constructor
class Person {
public firstName: string;
public lastName: string;
public constructor(init?: Partial<Person>) {
Object.assign(this, init);
}
function getName() {
return this.firstName + “ “ + this.lastName;
}
}
Pass the json into this constructor
let person = new Person({firstName: "A", lastName: "B" });
console.log(person);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论