[英]Parsing double values from JSON in Flutter and Dart
當我嘗試從 Flutter 中的 JSON 獲取雙精度值時遇到問題。
class MapPoint {
String title;
double lat;
double lng;
MapPoint({this.title, this.lat, this.lng});
factory MapPoint.fromJson(Map<String, dynamic> json) {
return MapPoint(
title: json["title"] as String,
lat: json["lat"] as double,
lng: json["lng"] as double
);
}
}
由於某種原因,我得到了錯誤
Dart 錯誤:未處理的異常:類型“雙”不是“字符串”類型的子類型
我嘗試了一些用戶double.parse(json["lng"])
,但得到了同樣的錯誤。
同時,這種從 JSON 獲取數據的方式適用於其他類型。
這是 JSON 示例
{
point: {
title: "Point title",
lat: 42.123456,
lng: 32.26567
}
}
Dart JSON 解析器將屬性轉換為 json 並且顯然足夠聰明,可以吐出 double 類型。
someVariable as double
需要左側的字符串。
可能發生的事情是您試圖將雙精度數轉換為雙精度數。
我會嘗試這樣的事情:
lat: json["lat"].toDouble(),
這將涵蓋 JSON 中的數據類似於“5”的情況。 在這種情況下,dart json 轉換器會將類型轉換為 int,如果您總是期待雙精度,它會破壞您的代碼。
我遇到了同樣的問題,我認為是這樣的:
class MapPoint {
String title;
double lat;
double lng;
MapPoint({this.title, this.lat, this.lng});
factory MapPoint.fromJson(Map<String, dynamic> json) {
return MapPoint(
title: json["title"] as String,
lat: json["lat"] is int ? (json['lat'] as int).toDouble() : json['lat'],
lng: json["lng"] is int ? (json['lng'] as int).toDouble() : json['lng']
);
}
}
我無法重現
void main() {
final json = {
"point": {"title": "Point title", "lat": 42.123456, "lng": 32.26567}
};
final p = MapPoint.fromJson(json);
print(p);
}
class MapPoint {
String title;
double lat;
double lng;
MapPoint({this.title, this.lat, this.lng});
factory MapPoint.fromJson(Map<String, dynamic> json) {
return MapPoint(
title: json["title"] as String,
lat: json["lat"] as double,
lng: json["lng"] as double);
}
}
我可以這樣解決這個問題
class MapPoint {
String title;
double lat;
double lng;
MapPoint({this.title, this.lat, this.lng});
factory MapPoint.fromJson(Map<String, dynamic> json) {
return MapPoint(
title: json["title"] as String,
lat: json["lat"] *1.0,
lng: json["lng"] *1.0
);
}
}
如果您的lat
字段可以為空,例如:
double? lat
在您的 fromJson 方法中,而不是:
lat: json["lat"] as double,
利用:
lat : double.tryParse(json['lat'].toString()),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.