JSON holds only data. Prototypes, methods, getters, Date objects, Maps and #private fields are lost, or become strings or {}. So you must convert both ways on purpose.
JSON to instance:
- Static factory:
Order.fromJSON(data)validates the input, turns strings back intoDates and builds nested objects. Clear, and no library needed. - class-transformer:
plainToInstance(CreateOrderDto, body)creates the class. Nested classes need@Type(() => LineDto). NestJS'sValidationPipewithtransform: truedoes this, then runs class-validator.
Instance to JSON:
- Add a
toJSON()method.JSON.stringifycalls it and uses its return value. - Or map to a response DTO in the controller.
- In NestJS,
ClassSerializerInterceptorwith@Exclude()onpasswordHashremoves it from every response.
Watch out:
structuredClonealso drops the prototype.- Values in a cache or queue may come from older code. Version them, or validate them when you read them.
- JSON keeps only data, so prototypes, methods and getters are lost.
- Dates become strings and must be converted back.
- A static
fromJSONfactory or class-transformer'splainToInstancerebuilds instances. - Nested classes need
@Typein class-transformer. - Control output with
toJSON, response DTOs or@ExcludewithClassSerializerInterceptor.