V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
scuuzqc

写了个 json 转 class 的小工具(轻喷)

  •  
  •   scuuzqc · Jul 26, 2020 · 1949 views
    This topic created in 2111 days ago, the information mentioned may be changed or developed.

    作为前端,由于自己对代码变量有洁癖~~只用驼峰,看不得下划线和驼峰混用,看着揪心。

    所以对于后端发过来的各种乱七八糟的变量,比如单字母,下划线变量,还有一些奇怪的数据(加密,二进制等),对于老接口,并不是接口协商能解决的,写了个小工具,算比较优雅的解决了~~

    用法:

    import { property, toClass, toPlain } 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',
    }
    
    const userModel = {
      id: 1234,
      name: 'name',
    };
    // use toPlain to convert plain object to class
    const userRaw = toPlain(userModel, UserModel);
    // you will get a class, just like below one
    {
      i: 1234,
      name: 'name',
    }
    
    

    支持双向转换~ 详情请参阅: https://www.npmjs.com/package/class-converter

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1426 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 23:59 · PVG 07:59 · LAX 16:59 · JFK 19:59
    ♥ Do have faith in what you're doing.