I am new to using the class-transformer. I created a simple product class and JSON string to load a Product. However, I get undefined, even though I see the output when I log the result like the transformation was successful. I removed the readonly, but it made no difference. Please help, I have spent so much time. The problem is reading the JSON from a json file does not work. When I use the JSOn as follows:
let prodJson = {
name: 'MyProduct,
productId: 'POOA',
description: 'A product'
}
etc. this works. If I read the JSON from a file, it doesn't.
export class Product{
@Expose()
public readonly name: string;
@Expose()
public readonly productId?: string;
@Expose()
public readonly description?: number;
}
const productJson = {\n"
" \"name\": \"Aerosol\",\n"
" \"productId\": \"ARSL\",\n"
" \"description\": \"Apply to living room\"\n"
"}"
createProduct(productJson: string){
return plainToInstance(Product, productJson);
}
const product = createProduct(productJson);
console.log('Product', product); // undefined
CodePudding user response:
createProduct(productJson: string){
return plainToInstance(Product, JSON.parse(productJson));
}
plainToInstance
: This method transforms a plain javascript object to instance of specific class. The second parameter not a json string. it should be an object.