class-transformer icon indicating copy to clipboard operation
class-transformer copied to clipboard

serialize nested objects using class-transformer

Open rahulkutah opened this issue 2 years ago • 1 comments

I am trying to serialize nested objects using a class transformer. I have two dtos like below. When I am trying to serialize using plainToClass the nested object gets removed from the output. only getting the parent object's data.

User dto:

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

    @Expose()
    first_name: string;

    @Expose()
    last_name: string;

    @Expose()
    profile: ProfileDto

}

Profile dto:

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

    @Expose()
    address: string;

    @Expose()
    pincode: string;
}

Serializer:

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

Expected Output:

{
    email:'[email protected]',
    first_name: 'test',
    last_name: 'test',
    profile: {
        date_of_birth: '',
        address: '',
        pincode: ''
    }
}

rahulkutah avatar Jul 02 '22 08:07 rahulkutah

@rahulkutah, have you tried decorator @Type for this? @Type(() => ProfileDto)

Kolobok12309 avatar Jul 16 '22 10:07 Kolobok12309