简体   繁体   中英

How can I change the property name of a serialized entity with toJSON?

I want to serialize a property with a different name than it has in the entity.

@Entity()
export class MyEntity {
  // This should be serialized with name_column in JSON
  @Column()
  name: string
}

When I call classToPlain I want the property name to be serialized to name_column :

classToPlain(myEntity)
// returns: {name: 'my name'}
// should be: {name_column: 'my name'}

Is there a specific reason you are using json-typescript-mapper instead of class-transformer , which is natively supported by nest.js?


With class-transformer , you can change the name of a column with @Expose :

@Expose({ name: "name_column" })
name: string;

For the serialization, you can just annotate your controller class or individual methods with @UseInterceptors(ClassSerializerInterceptor) . With the annotation, it will automatically serialize all entities, that you return from a controller method. You can read more about this in this thread .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM