如何从json转换为angular类
我有一个班叫book in angular如何从json转换为angular类,json,converter,angular6,Json,Converter,Angular6,我有一个班叫book in angular export class Book { name: String; auther: String; series: String; price: Number; publishDate: Date; ISBN: Number; promise: String; active: boolean; } 使用httpClient,我从服务器(json格式)获取书籍数据,如下所示 我想把json转换成book类,有没有相
export class Book
{
name: String;
auther: String;
series: String;
price: Number;
publishDate: Date;
ISBN: Number;
promise: String;
active: boolean;
}
使用httpClient,我从服务器(json格式)获取书籍数据,如下所示
我想把json转换成book类,有没有相应的包?
如果我如何从json对象中提取数据
更新:
这是我得到的json数据
ISBN:"req.body.ISBN"
author:"req.body.author"
created_at:"2018-08-06T11:53:07.532Z"
name:"a"
photo:""
publishDate:"2018-08-06T11:53:07.532Z"
sellDate:"2018-08-06T11:53:07.532Z"
seller:"req.body.seller"
seriesName:"4"
summary:"req.body.summary"
updated_at:"2018-08-06T11:53:17.629Z"
__v:0
_id:"5b6836aa5d6e0a2c481fbd04"
您可以使用一个简单的构造函数来接收如下对象:
export class Book
{
name: String;
auther: String;
series: String;
price: Number;
publishDate: Date;
ISBN: Number;
promise: String;
active: boolean;
constructor(obj: any) {
this.name = obj.name;
this.auther = obj.auther;
this.publishDate = new Date(obj.publishDate);
}
}
this.http.get(this.booksUrl)
.subscribe(res => new Book(res));
然后按如下方式更新您的请求:
export class Book
{
name: String;
auther: String;
series: String;
price: Number;
publishDate: Date;
ISBN: Number;
promise: String;
active: boolean;
constructor(obj: any) {
this.name = obj.name;
this.auther = obj.auther;
this.publishDate = new Date(obj.publishDate);
}
}
this.http.get(this.booksUrl)
.subscribe(res => new Book(res));
显然,我认为您会将新创建的图书与实例相关联,例如:
book: Book;
this.http.get(this.booksUrl)
.subscribe(res => {
this.book = new Book(res)
});
我最后使用了这个代码
getBookList() {
return this.http.get<Book[]>(this.bookUrl + '/list')
.subscribe(bookRes => this.books = bookRes);
}
getBookList(){
返回this.http.get(this.bookUrl+'/list')
.订阅(bookRes=>this.books=bookRes);
}
由于我得到了json中的响应,这个cast能够将任何同名的对象从json转换到Book。
例如,我在book中有一个author变量,只要它在json文档和book类中的名称相同,它就可以转换它,但如果在我的类中,我将这个变量称为“BooksAuthor”,因为它与json文档的名称不同,我就不能转换它我还有dates变量,我如何转换它们?这取决于你如何接收它们。发布一个收到的json请求它对我不起作用对象没有“name”属性或“author”属性但我找到了另一种编辑答案的方法。不过,请分享您的解决方案,在您的邮件中添加答案,并添加一个带有发布日期的示例