[英]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
我希望将属性name
序列化为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?您使用json-typescript-mapper
而不是 nest.js 原生支持的class-transformer
是否有特定原因?
With class-transformer
, you can change the name of a column with @Expose
:使用class-transformer
,您可以使用@Expose
更改列的名称:
@Expose({ name: "name_column" })
name: string;
For the serialization, you can just annotate your controller class or individual methods with @UseInterceptors(ClassSerializerInterceptor)
.对于序列化,您可以使用@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 .您可以在此线程中阅读有关此内容的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.