簡體   English   中英

如何從json轉換為angular類

[英]how to convert from json to angular class

我有一堂課叫角書

export class Book
{
  name: String;
  auther: String;
  series: String;

  price: Number;
  publishDate: Date;
  ISBN: Number;
  promise: String;


  active: boolean;
}

並使用httpClient像這樣從服務器(以json格式)獲取圖書的數據

this.http.get(this.booksUrl)
  .subscribe(res => console.log(res));

我想從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));

顯然,我認為您會將新創建的Book與實例相關聯,例如:

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);
  }

由於我在json中獲得了響應,因此此強制轉換能夠將json中具有相同名稱的任何對象強制轉換為Book。 例如,我在書中有一個author變量,因此只要它在json文檔中是相同的名稱,並且在book類中就可以對其進行轉換,但是如果在我的班級中,我將其稱為“ BooksAuthor”,因為與json文檔的名稱不同,我將無法強制轉換

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM