You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
How can I make json2typescript to use the name of the properties in the Coord and Size classes instead of using the name of the properties in the (common) base class Pair?
@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);
The text was updated successfully, but these errors were encountered:
You could also use custom converters and call the set/get methods there. But the decorator needs to be set to the field.
Custom converters are a good way to assign anything you want, not just simple strings. We could actually implement a solution where json2typescript automatically calls the get/set methods, if there are some. I will keep this open for future reference.
Please look at the below code. I expect the result of the serialization to be
Instead it is
How can I make json2typescript to use the name of the properties in the Coord and Size classes instead of using the name of the properties in the (common) base class Pair?
The text was updated successfully, but these errors were encountered: