typescript - 使用类转换器 : Nest js 序列化嵌套对象

我正在尝试使用类转换器序列化嵌套对象。我有两个如下所示的 dto。当我尝试使用 plainToClass 进行序列化时,嵌套对象会从输出中移除。只获取父对象的数据。

用户dto:

export class UserDto extends AbstractDto {
    @Expose()
    email: string;

    @Expose()
    first_name: string;

    @Expose()
    last_name: string;

    @Expose()
    profile: ProfileDto

}

简介dto:

export class ProfileDto extends AbstractDto {
    @Expose()
    date_of_birth: string;

    @Expose()
    address: string;

    @Expose()
    pincode: string;
}

序列化器:

const serialized = plainToClass(UserDto, user, {
    excludeExtraneousValues: true,
});

预期输出:

{
    email:'a@gmail.com',
    first_name: 'test',
    last_name: 'test',
    profile: {
        date_of_birth: '',
        address: '',
        pincode: ''
    }
}

最佳答案

我在这里找到了答案Link .如果我添加 enableImplicitConversion: true 以及 @Type 装饰器,那么它会按预期工作。

export class UserDto extends AbstractDto {
    @Expose()
    email: string;

    @Expose()
    first_name: string;

    @Expose()
    last_name: string;

    @Expose()
    @Type(() => ProfileDto)
    profile: ProfileDto

}

序列化器:

const serialized = plainToClass(UserDto, user, {
    excludeExtraneousValues: true,
    enableImplicitConversion: true
    
});

https://stackoverflow.com/questions/72836741/

相关文章:

r - 混合 glm 零膨胀模型的 Bootstrap 方法

java - ASM 和 Javaagent 字节码检测 : ClassFormatError: S

python - 将用户数据列表转换为对象的最佳方法是什么?

javascript - 用 JavaScript 数组中的空值替换空值/未定义值

javascript - 如何声明 useState() 初始值为 null,然后再给它一个对象值?

r - 如果数据集的某些列为空,我想在 R 中删除那些列

c - 格式说明符 : %u vs %d in C

r - 在R中按组计算每两行值的比例

excel - 分配给数组

android - 如何在 Android Jetpack Compose 的 TextField