Take a look at the code snippet below. I anticipate the serialized result to be:
{
"origin": {
"x": 1,
"y": 2
},
"size": {
"width": 3,
"height": 4
}
}
However, the actual result is:
{
"origin": {
"a": 1,
"b": 2
},
"size": {
"a": 3,
"b": 4
}
}
Is there a way to instruct json2typescript to use the property names in the Coord and Size classes instead of using the names from the common base class Pair?
I attempted to remove the @Json decorators from Pair, but then nothing is serialized in Coord and Size.
@JsonObject("Pair")
export class Pair2
{
@JsonProperty("a", Number)
protected a: number;
@JsonProperty("b", Number)
protected b: number;
constructor(a?: number, b?: number)
{
this.a = a;
this.b = b;
}
}
@JsonObject("Coord")
export class Coord2 extends Pair2
{
@JsonProperty("x", Number)
public get x(): number { return this.a; }
public set x(value: number) { this.a = value; }
@JsonProperty("y", Number)
public get y(): number { return this.b };
public set y(value: number) { this.b = value };
constructor(x?: number, y?: number)
{
super(x, y);
}
}
@JsonObject("Size")
export class Size2 extends Pair2
{
@JsonProperty("width", Number)
public get width(): number { return this.a; }
public set width(value: number) { this.a = value; }
@JsonProperty("height", Number)
public get height(): number { return this.b };
public set height(value: number) { this.b = value };
constructor(width?: number, height?: number)
{
super(width, height);
}
}
@JsonObject("Rectangle")
export class Rectangle2
{
@JsonProperty("origin", Coord2)
origin: Coord2;
@JsonProperty("size", Size2)
size: Size2;
constructor(origin: Coord2, size: Size2)
{
this.origin = origin;
this.size = size;
}
}
let jsonConvert: JsonConvert = new JsonConvert();
jsonConvert.operationMode = OperationMode.LOGGING; // print some debug data
jsonConvert.ignorePrimitiveChecks = false; // don't allow assigning number to string etc.
jsonConvert.valueCheckingMode = ValueCheckingMode.DISALLOW_NULL; // never allow null
let origin = new Coord2(1, 2);
let size = new Size2(3, 4);
let rectangle = new Rectangle2(origin, size);
let rectangleJsonObj = jsonConvert.serialize(rectangle);
console.log(rectangleJsonObj);
let rectangleStr = JSON.stringify(rectangleJsonObj);
console.log(rectangleStr);