问题
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'}
回答1:
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.
来源:https://stackoverflow.com/questions/54250910/how-can-i-change-the-property-name-of-a-serialized-entity-with-tojson