【问题标题】:How to map JSON data to a class如何将 JSON 数据映射到类
【发布时间】:2015-08-01 02:39:10
【问题描述】:

我通过Babel 创建了一个 ES6 类,我想将从服务器获取的 JSON 数据映射到 ES6 类。
有什么常用的方法吗?

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?

【问题讨论】:

    标签: javascript ecmascript-6 babeljs


    【解决方案1】:

    我会使用Object.assign将JSON对象合并到this中,如下:

    class User {
      firstName;
      lastName;
      sex;
    
      constructor(data) {
        Object.assign(this, data);
    //  ^^^^^^^^^^^^^^^^^^^^^^^^^^
      }
    }
    
    var data = JSON.parse(req.responseText);
    new User(data);
    

    【讨论】:

    • 你的回答让我感到疑惑(希望有人能给我一个答案),但是这个 plain 构造函数现在不再定义任何User属性违背了具有类定义的目的。您能否将属性添加到您的答案中作为示例?
    • Object.assign 的解决方案仅在没有某些类类型的属性时才有效。如果Useraddress,我们需要在User 构造函数中调用this.address = new Address(data.address)
    【解决方案2】:

    您可以使用这个 npm 包 https://www.npmjs.com/package/class-converter 将所有 JSON 映射到一个类。 它看起来像以下一个:

    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',
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2016-10-22
      • 2018-06-19
      • 2013-06-16
      • 2011-08-05
      • 2020-06-26
      相关资源
      最近更新 更多