CodePark/ questions / Serializing class instances
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › Serializing class instances

Request bodies, cache values and queue messages arrive as plain JSON. How do you turn them into class instances, and how do you control what a class instance looks like in API responses?

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 into Dates and builds nested objects. Clear, and no library needed.
  • class-transformer: plainToInstance(CreateOrderDto, body) creates the class. Nested classes need @Type(() => LineDto). NestJS's ValidationPipe with transform: true does this, then runs class-validator.

Instance to JSON:

  • Add a toJSON() method. JSON.stringify calls it and uses its return value.
  • Or map to a response DTO in the controller.
  • In NestJS, ClassSerializerInterceptor with @Exclude() on passwordHash removes it from every response.

Watch out:

  • structuredClone also 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 fromJSON factory or class-transformer's plainToInstance rebuilds instances.
  • Nested classes need @Type in class-transformer.
  • Control output with toJSON, response DTOs or @Exclude with ClassSerializerInterceptor.