简体   繁体   中英

how to convert from json to angular class

I have a class named book in angular

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

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


  active: boolean;
}

and using httpClient I get the book's data from the server (in json format) like so

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

I want to convert from json to the book class, is there a package for that? if how can I extract the data from the json object

UPDATE: this is the json data I get

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"

You can use a simple constructor that receives an Object like this:

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

Then update you request like this:

this.http.get(this.booksUrl)
  .subscribe(res => new Book(res));

Obviously I think you would associate new created Book with an instance, something like:

book: Book;

this.http.get(this.booksUrl)
      .subscribe(res => {
           this.book = new Book(res)
});

I used this code in the end

getBookList() {
    return this.http.get<Book[]>(this.bookUrl + '/list')
        .subscribe(bookRes => this.books = bookRes);
  }

since the I got the respond in json this cast was able to cast any object of the same name from json to Book. for example I have an author variable in book so as long it's the same name in the json document and in the book class it will be able to cast it, but if in my class i'll call this variable "BooksAuthor" ,since it's a diffrent name than the json document I won't be able to cast it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM