控制打字稿中json序列化的顺序

THB*_*BFT 0 serialization json geojson typescript

我正在序列化一个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();
    }
}
Run Code Online (Sandbox Code Playgroud)

运用 JSON.stringify(new Point([10, 10]));

到目前为止,这很好,但最终被插入GeoJSON对象并且属性的顺序很重要.我得到的是:

{"coordinates":[10,10],"type":"Point"}
Run Code Online (Sandbox Code Playgroud)

我需要的是:

{"type":"Point","coordinates":[10,10]}
Run Code Online (Sandbox Code Playgroud)

如果不在public coordinates构造函数中声明并分配它们:

constructor(coordinates: Coordinate | number[]) {
   super();
   this.coordinates = coordinates;
}
Run Code Online (Sandbox Code Playgroud)

结果是对的.作为一个极简主义者,我试图使用public参数使用构造函数.

有没有办法控制JSON.stringify(-)方法中属性的顺序?


给自己一个替代的答案

真正的问题在于properties特征的价值(在原始问题的范围之外).通过覆盖toJSON对象上的方法,可以控制对象如何序列化自身.我在Geometry课堂上添加了以下内容,一切都很顺利.

public toJSON() {
    return {
        type: this.type,
        coordinates: this.coordinates,
    };
}
Run Code Online (Sandbox Code Playgroud)

我做了进一步装饰我的上游FeatureFeatureCollection课程.

Alb*_*res 5

您可以将第二个参数传递给JSON.stringify具有所需顺序的属性名称的数组.

例如:

JSON.stringify(new Point([10, 10]), ['type', 'coordinates']);
Run Code Online (Sandbox Code Playgroud)