1

我有财产的User对象firstName。我想反序列化它,first_name但将它序列化为firstName.

我的打字稿代码:

import { Expose, Exclude, classToPlain, plainToClass } from "class-transformer";
import "reflect-metadata";

@Exclude()
class User {
  @Expose({ name: "first_name", toClassOnly: true })
  firstName: string;

  constructor(s: Partial<User> = {}) {
    Object.assign(this, s);
  }
}

const user = plainToClass(User, { first_name: "Mari" });
console.log(user); // { firstName: "Mari" }

const plainSettings = classToPlain(user);
console.log(plainSettings); // { first_name: "Mari" }

现场演示

我想classToPlain将属性序列化为firstName. 使用 double@Expose忽略第二个:

@Expose({ name: "first_name", toClassOnly: true })
@Expose({ name: "firstName", toClassOnly: false})
firstName: string;
// the same behaviour

有没有办法序列化/反序列化具有不同属性名称的对象?

4

1 回答 1

0

***已编辑我刚刚意识到您正在尝试更改属性的名称。这不是我能帮忙的。我认为这只是类序列化/反序列化。

我刚刚打了几天这场战斗,我想我终于破解了它。这是对我有用的示例用户和地址。

import * as clone from 'clone'
import Address, { AddressFactory } from './Address'
import { classToPlain, plainToClass, Type } from 'class-transformer'

export class User {

name: string
userID: string

@Type(() => Address)
address: Address

constructor(name: string, userID: string, address: Address) {
    this.name = name
    this.userID = userID
    this.address = address
}
copyObject(): User {
    return clone<User>(this)
}

getObjectForSaving(): Record<string, unknown> {
    return classToPlain(this)
}
}
export default User

export class UserFactory {
static fromVoid(): User {
    return new User('name', 'userID', AddressFactory.fromVoid())
}
static fromJSON(jsonObjectData: User): User {
    return plainToClass(User, jsonObjectData)
}
}

然后是地址模型

import { classToPlain, plainToClass } from "class-transformer"
import * as clone from 'clone'

export class Address {
    num: number
    street: string
    city: string
    state: string
    zip: number
    constructor(num: number, street: string, city: string, state: string, zip: number) {
        this.num = num
        this.street = street
        this.city = city
        this.state = state
        this.zip = zip
    }

    copyObject(): Address {
        return clone<Address>(this)
    }
    getObjectForSaving(): Record<string, unknown> {
        return classToPlain(this)
    }
}
export default Address


export class AddressFactory {
    static fromVoid(): Address {
        return new Address(0, '', '', '', 0)
    }
    static fromJSON(jsonObjectData: Address): Address {
        return plainToClass(Address, jsonObjectData)
    }
}

我使用工厂函数来生成新对象。可以是新的默认对象,也可以使用静态 fromJSON 构造函数实例化新的类实例。如果需要,您还可以创建其他工厂构造函数。

最后,我在 Redux 中更新状态时使用复制对象快速复制对象,以帮助实现不变性等...

祝你好运!

于 2021-04-04T17:52:18.320 回答