私は活字体クラスオブジェクト直列化していますにJSONシリアライズの順序を制御:は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;
}
結果は正しい。ミニマリストなので、私はpublicパラメータを使ってコンストラクタでこれを動作させようとしています。
JSON.stringify(-)
メソッドのプロパティの順序を制御する方法はありますか?
自分自身に別の答えを与える
本当の問題は、(元の質問の範囲外)機能のproperties
値としました。オブジェクトのtoJSON
メソッドをオーバーライドすることによって、オブジェクトがそれ自身をどのように直列化するかを制御することが可能です。私は次のものを私のGeometry
クラスに加えました。
public toJSON() {
return {
type: this.type,
coordinates: this.coordinates,
};
}
私はさらに、よく私の上流Feature
とFeatureCollection
クラスを飾るために作られました。
感謝。 – THBBFT
喜んで:) –