【问题标题】:controlling the order of json serialization in typescript控制打字稿中json序列化的顺序
【发布时间】: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,
    };
}

我还进一步装饰了我的上游 FeatureFeatureCollection 类。

【问题讨论】:

    标签: json typescript serialization geojson


    【解决方案1】:

    您可以将第二个参数传递给JSON.stringify,其中包含一个数组,其中的属性名称按所需顺序排列。

    例如:

    JSON.stringify(new Point([10, 10]), ['type', 'coordinates']);
    

    【讨论】:

    • 感谢您为我指明了正确的方向并最终使我成为 RTFM
    • 很高兴为您提供帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 2015-05-26
    相关资源
    最近更新 更多