【发布时间】:2017-11-20 11:21:01
【问题描述】:
我正在序列化一个 Typescript 类对象:
class Geometry {
public abstract type: string;
public abstract coordinates: Coordinates | number[];
}
class Point extends Geometry {
public readonly type: string = "Point";
constructor(public coordinates: Coordinate | number[]) {
super();
}
}
使用JSON.stringify(new Point([10, 10]));
到目前为止一切都很好,然而,这最终被插入到一个 GeoJSON 对象中,并且属性的顺序很重要。我得到的是:
{"coordinates":[10,10],"type":"Point"}
我需要的是:
{"type":"Point","coordinates":[10,10]}
如果不在构造函数中声明public coordinates并赋值:
constructor(coordinates: Coordinate | number[]) {
super();
this.coordinates = coordinates;
}
结果是正确的。作为一个极简主义者,我试图让它与使用公共参数的构造函数一起工作。
有没有办法控制JSON.stringify(-)方法中属性的顺序?
给自己另一个答案
真正的问题在于功能的properties 值(超出了原始问题的范围)。通过覆盖对象上的toJSON 方法,可以控制对象如何序列化自身。我将以下内容添加到我的 Geometry 课程中,一切都很好。
public toJSON() {
return {
type: this.type,
coordinates: this.coordinates,
};
}
我还进一步装饰了我的上游 Feature 和 FeatureCollection 类。
【问题讨论】:
标签: json typescript serialization geojson