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

南楼画角 提交于 2021-02-11 14:01:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!