首页 > 解决方案 > Angular:将带有自定义参数的JSON映射到对象

问题描述

我是 Angular 的新手,所以我的问题的解决方案可能很简单,尽管我很难找到它。该问题与通过打字稿映射到对象的 JSON 相关联。如何映射简单数据类型非常明显,但在我的例子中,我有一个 JSON 对象,它带有一个表示自定义数据格式的字符串参数。它看起来是这样的:

{
            "id": 2,
            "coordinates": "POLYGON ((93.85459125041562 2.2894918584196797, 93.85478973388572 2.2894543170028445, 93.85515987873577 2.2895723043110532, 93.8554173707562 2.2897761005578046))"
        }

我试图在构造函数中解析它,但它似乎没有调用:

    export class RegionModel {
      public _pointsType: string;
  public _points: CoordinateModel[];
  public _centerPoint: CoordinateModel;

  constructor(
    public id: number,
    public coordinates: string
  ) {

    const regex = /([^\)\(]+)(?=\))/g;

    if (coordinates != null && coordinates.length > 0) {
      let longSum = 0;
      let latSum = 0;
      const str = regex.exec(coordinates)[0];
      str.replace(/^\s+|\s+$/g, '').split(',').forEach((value, index, array) => {
        const longLatString = value.replace(/^\s+|\s+$/g, '').split(' ');
        latSum += Number(longLatString[1]);
        longSum += Number(longLatString[0]);
        this._points.push(new CoordinateModel(
          Number(longLatString[1]), Number(longLatString[0]))
        );
      });
      this._centerPoint = new CoordinateModel(
        latSum / this._points.length,
        longSum / this._points.length
      );
    }

get points(): CoordinateModel[] {
    return this._points;
  }

  get pointsType(): string {
    return this._pointsType;
  }

  get centerPoint(): CoordinateModel {
    return this._centerPoint;
  }

  set centerPoint(value: CoordinateModel) {
    this._centerPoint = value;
  }

  set coordinates(value: CoordinateModel[]) {
    this._coordinates = value;
  }
  }

export class CoordinateModel {
      constructor(
        public lat: number,
        public lon: number
      ) {}
    }

谁能帮我找到一个好的解决方案来解析这种数据?

标签: angulartypescriptangular5

解决方案


我的方法是使用正则表达式来捕获坐标:

const coordinatesArray = coordinates.match(/(\d+\.\d+)\s(\d+\.\d+)/g);
this._points = coordinatesArray.reduce((acc, current) => {
  const latLong = current.split(" ");
  acc.push(
    new CoordinateModel(Number(latLong[0]), Number(latLong[1]))
  );
  return acc;
}, []);

如果你说你的构造函数没有被调用是因为你没有按预期使用你的类,即new RegionModel(id, coordinates).

注意:在构造函数中解析你的字符串会很好,这样你就可以从你的逻辑的其余部分隐藏实现细节,如果你需要改变你解析字符串的方式(由于另一个字符串表示),你只需要更新RegionModel课程。

希望能帮助到你!


推荐阅读