Home > Software design >  Transform json to class intstance with class-transformer
Transform json to class intstance with class-transformer

Time:01-27

I would like to create an instance of the Customer class from Json object.

But using the plainToInstance function of class-transformer I don't have the proper class instance as a type save typescript object.

What I'm doing bad?

Import

import { plainToInstance } from 'class-transformer';

Customer JSON

    const json = `{
      "id": "1",
      "name": "Jogn",
      "surname": "Doe",
      "email": "[email protected]",
      "phone": "123456789"
  }
}
`;

Customer class definition

import { Field, ObjectType, Directive, ID } from '@nestjs/graphql';
import { Address } from './address';

@ObjectType()
@Directive('@key(fields: "id")')
export class Customer {

  @Field(() => ID)
  id: string;

  @Field()
  name: String;

  @Field({nullable: true})
  surname?: String;

  @Field()
  email: String;

  @Field({nullable: true})
  phone?: String;

  @Field()
  customerType: String;

  @Field()
  customerStatus: String;

  @Field(() => [Address], { nullable: true })
  addresses?: [Address]
}

Transformation from Json to Customer instance

let customer : Customer = plainToInstance(Customer, json) as Customer;
console.log('customer.email);

Console result

Customer email: undefined

So I couldn't get the email of the customer here

This is what I have when I log the entire customer variable

console.log(customer);

{
      "id": "1",       
      "name": "Jogn",  
      "surname": "Doe",
      "email": "[email protected]",
      "phone": "123456789"
}

Test with creating the Customer instance inline

var x = new Customer();
x.id = "123";
console.log(x)

So, now the object looks properly in the console

Customer { id: '123' }

CodePudding user response:

You must pass a json object to plainToInstance - not a string.
i.e. your json variable should be

const json = {
  id: '1',
  name: 'Jogn',
  surname: 'Doe',
  email: '[email protected]',
  phone: '123456789',
};

here's a working Stackblitz example

CodePudding user response:

The second attribute of plainToInstance should be a plain object so you have to parse your json string into an object:

let customer = plainToInstance<Customer, object>(Customer, JSON.parse(json))
  • Related