Javascript Angular 5/Typescript-如何将复杂的json对象强制转换为类

Javascript Angular 5/Typescript-如何将复杂的json对象强制转换为类,javascript,node.js,angular,typescript,mongoose,Javascript,Node.js,Angular,Typescript,Mongoose,我试图将一个复杂的(多类型类)json响应对象(从我的nodejs/mongoose后端接收)强制转换为一个typescript类 矩类包含user类型的作者和comment类型的comments数组 力矩.模型.ts import { Comment } from './comment.model'; import { User } from './user.model'; export class Moment { _id?: string = null; bod

我试图将一个复杂的(多类型类)json响应对象(从我的nodejs/mongoose后端接收)强制转换为一个typescript类

矩类包含user类型的作者和comment类型的comments数组

力矩.模型.ts

    import { Comment } from './comment.model';
import { User } from './user.model';

export class Moment {

    _id?: string = null;
    body?: string = null;
    _author?: User = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    _comments?: Comment[] = [];
    created_at?: string = null;
    updated_at?: string = null;


    constructor(data?: Moment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Moment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

    public get author(): User {
        return this._author;
    }
    public set author(data: User) {
        this._author = new User(data);
    }

    public get comments(): Comment[] {
        return this._comments;
    }
    public set comments(data: Comment[]) {
        this._comments = data.map(c => new Comment(c));
    }
}
comment.model.ts

    export class Comment {

    _id?: string = null;
    body?: string = null;
    moment?: any = null;
    author?: any = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    parent?: any = null;
    replies?: any = null;
    updated_at?: string = null;
    created_at?: string = null;

    constructor(data?: Comment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Comment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

}
 export class User {

    _id?: string = null
    updated_at?: string = null;
    created_at?: string = null;
    profile?: any = null;
    phone?: any = null;
    email?: any = null;
    followers: any[] = [];
    following: any[] = [];
    isOnline: any = null;
    socketId: any = null;


    constructor(data?: User) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: User) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }
    get(moment_id) {

    let endpoint = this.path + moment_id;

    return this.apiService.get(endpoint)
        .map((res) => new Moment(res.data));

}
this.route.params.switchMap((params) => {
    let moment_id = params['id'];
    return this.momentService.get(moment_id);
}).subscribe((res) => {

    this.moment = res;
    console.log(this.moment);
});
user.model.ts

    export class Comment {

    _id?: string = null;
    body?: string = null;
    moment?: any = null;
    author?: any = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    parent?: any = null;
    replies?: any = null;
    updated_at?: string = null;
    created_at?: string = null;

    constructor(data?: Comment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Comment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

}
 export class User {

    _id?: string = null
    updated_at?: string = null;
    created_at?: string = null;
    profile?: any = null;
    phone?: any = null;
    email?: any = null;
    followers: any[] = [];
    following: any[] = [];
    isOnline: any = null;
    socketId: any = null;


    constructor(data?: User) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: User) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }
    get(moment_id) {

    let endpoint = this.path + moment_id;

    return this.apiService.get(endpoint)
        .map((res) => new Moment(res.data));

}
this.route.params.switchMap((params) => {
    let moment_id = params['id'];
    return this.momentService.get(moment_id);
}).subscribe((res) => {

    this.moment = res;
    console.log(this.moment);
});
时刻服务.ts

    export class Comment {

    _id?: string = null;
    body?: string = null;
    moment?: any = null;
    author?: any = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    parent?: any = null;
    replies?: any = null;
    updated_at?: string = null;
    created_at?: string = null;

    constructor(data?: Comment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Comment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

}
 export class User {

    _id?: string = null
    updated_at?: string = null;
    created_at?: string = null;
    profile?: any = null;
    phone?: any = null;
    email?: any = null;
    followers: any[] = [];
    following: any[] = [];
    isOnline: any = null;
    socketId: any = null;


    constructor(data?: User) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: User) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }
    get(moment_id) {

    let endpoint = this.path + moment_id;

    return this.apiService.get(endpoint)
        .map((res) => new Moment(res.data));

}
this.route.params.switchMap((params) => {
    let moment_id = params['id'];
    return this.momentService.get(moment_id);
}).subscribe((res) => {

    this.moment = res;
    console.log(this.moment);
});
力矩细节.组件.ts

    export class Comment {

    _id?: string = null;
    body?: string = null;
    moment?: any = null;
    author?: any = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    parent?: any = null;
    replies?: any = null;
    updated_at?: string = null;
    created_at?: string = null;

    constructor(data?: Comment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Comment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

}
 export class User {

    _id?: string = null
    updated_at?: string = null;
    created_at?: string = null;
    profile?: any = null;
    phone?: any = null;
    email?: any = null;
    followers: any[] = [];
    following: any[] = [];
    isOnline: any = null;
    socketId: any = null;


    constructor(data?: User) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: User) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }
    get(moment_id) {

    let endpoint = this.path + moment_id;

    return this.apiService.get(endpoint)
        .map((res) => new Moment(res.data));

}
this.route.params.switchMap((params) => {
    let moment_id = params['id'];
    return this.momentService.get(moment_id);
}).subscribe((res) => {

    this.moment = res;
    console.log(this.moment);
});

当我调用我的服务时,我将json分配给一个新的时刻类。在组件中,我尝试打印这个.moment。除了作者和注释是空的之外,一切都很好。

您可以尝试以下方法

this[key]=(key=''u author'?新用户(data[key]):(key=''u comments'?新评论(data[key]):data[key])


你可以试试类似的东西

this[key]=(key=''u author'?新用户(data[key]):(key=''u comments'?新评论(data[key]):data[key])



您在
Moment
中的
反序列化
方法以相同的方式处理每个字段,只是从JSON复制值。这意味着它从不构造
User
Comment
对象。您可能应该“手工”编写它来正确处理每个属性,而不是使用循环。

您的
反序列化
方法在
时刻
以相同的方式处理每个字段,只是从JSON复制值。这意味着它从不构造
User
Comment
对象。您可能应该“手工”编写,以正确处理每个属性,而不是使用循环。

\u author
属于
User
类型,只有在调用like
new User(数据[键])时,才会将值分配给的成员。
。否则,由于类型兼容性,您将得到错误,并给出预期的null。如果您提供一个示例,我们可以更轻松地测试它。你不觉得吗?我还认为您应该删除javascript标签,因为在这段代码中没有任何javascript代码(即使您使用node.js作为后端)。和好奇一样,为什么要使用复制构造函数(在构造函数内部反序列化)?你真的需要它吗?@santoshegde ye我想我理解这个问题,有解决方案吗?@JTejedor是的,我需要它,这就是重点,我试图将json数据转换为一个typescript类。这不是真正的转换。您正在构造一个
时刻
(使用
新时刻
),但我看不到其他类在任何地方被调用?
\u author
类型为
User
,只有在调用like
new User(数据[key])
时,才会将值分配给的成员。否则,由于类型兼容性,您将得到错误,并给出预期的null。如果您提供一个示例,我们可以更轻松地测试它。你不觉得吗?我还认为您应该删除javascript标签,因为在这段代码中没有任何javascript代码(即使您使用node.js作为后端)。和好奇一样,为什么要使用复制构造函数(在构造函数内部反序列化)?你真的需要它吗?@santoshegde ye我想我理解这个问题,有解决方案吗?@JTejedor是的,我需要它,这就是重点,我试图将json数据转换为一个typescript类。这不是真正的转换。您正在构建一个
时刻
(使用
新时刻
),但我看不到其他类在任何地方被调用?是的,我不需要getter和setter,只需要重建我的类。我只是想知道这有多有效。在什么意义上有效?很少值得为这样的事情担心运行时效率。更重要的是要考虑维护性。对不起,这就是我的意思,我试图把一些与函数相关的函数重构成模型,而不是将它们分散在组件中。是的,我不需要吸气剂和定位器,只需要重建我的类。我只是想知道这有多有效。在什么意义上有效?很少值得为这样的事情担心运行时效率。更重要的是要考虑维护性。抱歉,这就是我的意思,我正试图重构一些与模型相关的函数,而不是将它们分散在组件中。谢谢,虽然这是正确的解决方案,但它帮助我更好地重新编写代码。虽然这不是正确的解决方案,但它帮助我更好地重新编写代码。它写得不好。