【问题标题】:Json int to double parsing FlutterJson int 对 Flutter 进行双重解析
【发布时间】:2021-02-02 04:54:09
【问题描述】:

问题是我想从这个解析: {"cost": 0} 加倍。所以我现在拥有的:

  1. json['cost'].toDouble(),错误:未处理的异常:NoSuchMethodError:类'String'没有实例方法'toDouble'。
  2. int.parse(json['cost']).toDouble(), error: Unhandled Exception: type 'int' is not a subtype of type 'String'
  3. json['cost'],错误:未处理的异常:类型'int'不是类型'double'的子类型

完整代码:

factory ShippingMethod.fromJson(Map<String, dynamic> json) {
    dynamic cost = json['cost'];
    print(cost.runtimeType);  // printing runtime type and I get it twice!
    return ShippingMethod(
      code: json['code'],
      title: json['title'],
      description: json['description'],
      cost: cost.toDouble(),
      taxClassId: json['tax_class_id'],
    );
  }

然后打印:

I/flutter (  480): int    // first it gives me int 
I/flutter (  480): String  // second it gives me String
E/flutter (  480): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: Class 'String' has no instance method 'toDouble'.
E/flutter (  480): Receiver: "0"
E/flutter (  480): Tried calling: toDouble()

此外,这是我从服务器获得的:

...
"pickup": {
                        "code": "pickup.pickup",
                        "title": "Standard",
                        "description": "If the cost of the order ...",
                        "cost": 0,
                        "tax_class_id": 0,
                        "text": "0.00 TMT"
                    }
...

Dart 成就了我的一天!.. 是 bug 还是什么?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:
    1. 要将字符串转换为双精度,我们有一个函数:double.parse(String)
    2. json["cost"] 正在返回一个 int 值,因此我们应该将其转换为字符串,然后我们可以将其传递给“double.parse(String)”。

    解决方案代码:

    double.parse(json["cost"].toString());
    

    【讨论】:

    • 魔术“toString”))
    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 2011-04-17
    • 2019-06-14
    • 2023-04-02
    • 2020-11-25
    • 2021-07-13
    • 2021-11-11
    • 2020-06-26
    相关资源
    最近更新 更多