While using JSON.stringify in Typescript, I encountered an issue where not all properties of the outermost object were being stringified. Here is the code snippet that showcases the problem:
class Criterion {
'@CLASS' = 'xyz.abc.Criterion'
operator: string;
operand: string[];
field: string;
constructor(field:string,operator:string,operand: string[]) {
this.field = field;
this.operator = operator;
this.operand = operand;
}
}
class Filter {
'@CLASS': 'xyz.ada.Filter';
criteria: Criterion[];
constructor(criteria:Criterion[]) {
this.criteria=criteria;
}
}
var criterion = new Criterion("a","b",["c"]);
var a = new Filter([criterion]);
JSON.stringify(a);
console.log(JSON.stringify(a));
Output:
{"criteria":[{"@CLASS":"xyz.abc.Criterion","field":"a","operator":"b","operand":["c"]}]}
Expected:
{"@CLASS":"xyz.ada.Filter","criteria":[{"@CLASS":"xyz.abc.Criterion","field":"a","operator":"b","operand":["c"]}]}
The issue lies in the fact that the @CLASS property of the Filter class object is not being properly stringified.