在 Flutter 和 Dart 中解析来自 JSON 的双值

moo*_*der 7 double json dart flutter

我在 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
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

由于某种原因,我得到了错误

Dart 错误:未处理的异常:“double”类型不是“String”类型的子类型

我尝试了一些用户,double.parse(json["lng"])但得到了同样的错误。
同时,这种从 JSON 获取数据的方式也适用于其他类型。

这是 JSON 示例

{ 
   point: {
     title: "Point title",
     lat: 42.123456,
     lng: 32.26567
  }
}
Run Code Online (Sandbox Code Playgroud)

Gil*_*nti 23

Dart JSON 解析器将属性转换为 json 并且显然足够聪明,可以吐出 double 类型。

someVariable as double 期望左侧有一个字符串。

可能发生的事情是您试图将双精度数转换为双精度数。

我会尝试这样的事情:

lat: json["lat"].toDouble(),

Run Code Online (Sandbox Code Playgroud)

这将涵盖 JSON 中的数据类似于“5”的情况。在这种情况下,dart json 转换器会将类型转换为 int,如果您总是期待双精度,它会破坏您的代码。

  • 如果您不确定类型是 int 还是 double;最好将其声明为“num” (2认同)

Mat*_*lli 8

我也遇到了同样的问题,我认为是这样的:

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']
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*eia 6

重写你的fromJson方法如下:

factory MapPoint.fromJson(Map<String, dynamic> json) {
    return MapPoint(
        title: json["title"] as String,
        lat : double.parse(json["lat"].toString()),
        lng : double.parse(json["lng"].toString()),
    );
  }
Run Code Online (Sandbox Code Playgroud)

如果您的lat字段可为空,例如:

double? lat
Run Code Online (Sandbox Code Playgroud)

在你的fromJson方法中,而不是:

lat : double.parse(json["lat"].toString()),
Run Code Online (Sandbox Code Playgroud)

使用:

lat : double.tryParse(json["lat"].toString()),
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 2

我无法重现

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);
  }
}
Run Code Online (Sandbox Code Playgroud)