Mapping JSON into Class Objects

后端 未结 5 910
你的背包
你的背包 2020-12-19 05:15

I am trying to map my JSON file into a class object, and then update the cards based on the newly received JSON.

My JSON structure is like this

 {
          


        
5条回答
  •  [愿得一人]
    2020-12-19 05:54

    this pkg can help you convert JSON to a class instance. https://www.npmjs.com/package/class-converter

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

提交回复
热议问题