简体   繁体   English

如何使用 toJSON 更改序列化实体的属性名称?

[英]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.

相关问题 如何在Geddy中更改属性的类型 - How can I change the type of a property in Geddy 如何更改 _nuxt 文件夹的名称? - How can I change the name of the _nuxt folder? 如何更改此 object 属性分配以避免原型污染 - How can I change this the object property assignment to avoid prototype pollution 我如何更改字段名称作为函数参数mongoDB - How can i change the name of a field as a function argument mongoDB 如何使用 nodeJS 和 discordJS 更改 Discord 频道名称? - How can I change a Discord channel name using nodeJS and discordJS? 如何更改“ ng2-file-upload”默认行为,以将输入的文件的名称属性更改为“ file” - How can i change 'ng2-file-upload' default behavior to change the name attribute of the file input to 'file' 如何将实体的实体关键字分配为数据存储区(Node JS)中其他实体的属性? - How do I assign an entity key of entity as a property of different entity in datastore (Node JS)? 我如何从一个函数继承而又不增加使用'name'属性的能力? - How can I inherit from a function without bollocksing the ability to use the 'name' property? 为什么我不能在 typeorm 中更改实体的构造函数 - Why can't I change the entity's constructor in typeorm 为什么我无法访问同名的父 class 属性? - Why can't I access to the parent class property with the same name?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM