简体   繁体   中英

How to map JSON data to a class

I created a ES6 class by Babel and I want to map JSON data which is gotten from a server to the ES6 class.
Is there anything common way to do that?

User.js

export default class User {
  constructor() {
    this.firstName;
    this.lastName;
    this.sex;
  }
}

app.js

import User from "./classes/User";

var data = JSON.parse(req.responseText);
console.log(data.firstname); //Bob
//now...just set data one by one?

I would merge the JSON object into this using Object.assign , as follows:

class User {
  firstName;
  lastName;
  sex;

  constructor(data) {
    Object.assign(this, data);
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^
  }
}

var data = JSON.parse(req.responseText);
new User(data);

you can use this npm package https://www.npmjs.com/package/class-converter to map all JSON to a class. it looks like following one:

import { property, toClass } from 'class-convert';

class UserModel {
  @property('i')
  id: number;

  @property()
  name: string;
}

const userRaw = {
  i: 1234,
  name: 'name',
};

// use toClass to convert plain object to class
const userModel = toClass(userRaw, UserModel);
// you will get a class, just like below one
{
  id: 1234,
  name: 'name',
}

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