angular - 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
) {}
}
谁能帮我找到一个好的解决方案来解析这种数据?
解决方案
我的方法是使用正则表达式来捕获坐标:
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
课程。
希望能帮助到你!
推荐阅读
- javascript - 试图让 JavaScript 回调以非阻塞方式工作
- python - 如何在视图中更改 Django 数据库模式?
- r - R中数据帧之间的匹配和替换
- java - 使用 Java 创建一个将 Int 转换为 String 的方法
- c# - 如何避免 MVC5 + Identity 中的会话劫持?/ 使cookie服务器端无效
- python - pythonw - 无法导入大多数(如果不是全部)站点包,甚至一些内置模块
- python - 当我输入 3 时,我得到打印 4 次的结果。你能告诉我为什么会这样吗?我是 python 新手
- python - 在类范围内导入模块的类型提示
- c++ - 如何调试 WebKit2GTK+ 扩展
- php - Nginx cors 启用 html 文件不起作用