json - 'int'类型不是 'double'类型的子类型— Dart/flutter 错误

标签 json flutter dart

因此,我有一个API设置,可以在调用时在特定端点上返回以下输出:

{
    "total_user_currency": 0.1652169792,
    "total_sats": 2184,
    "total_btc": 0.00002184,
    "outputArray": [
        {
            "txid": "642fd534cb3a670a31f4d59e70452b133b0b461d871db44fcc91d32bb6b6f0cc",
            "vout": 2,
            "status": {
                "confirmed": true,
                "block_height": 625673,
                "block_hash": "0000000000000000000310649c075b9e2fed9b10df2b9f0831efc4291abcb7fb",
                "block_time": 1586732907
            },
            "value": 546
        },

    ]
}

我正在使用以下dart类将JSON解码为可以与之交互的对象:
class UtxoData {
  final dynamic totalUserCurrency;
  final int satoshiBalance;
  final dynamic bitcoinBalance;
  List<UtxoObject> unspentOutputArray;

  UtxoData({this.totalUserCurrency, this.satoshiBalance, this.bitcoinBalance, this.unspentOutputArray});

  factory UtxoData.fromJson(Map<String, dynamic> json) {
    var outputList = json['outputArray'] as List;
    List<UtxoObject> utxoList = outputList.map((output) => UtxoObject.fromJson(output)).toList(); 

    return UtxoData(
      totalUserCurrency: json['total_user_currency'],
      satoshiBalance: json['total_sats'],
      bitcoinBalance: json['total_btc'],
      unspentOutputArray: utxoList
    );
  }
}

class UtxoObject {
  final String txid;
  final int vout;
  final Status status;
  final int value;

  UtxoObject({this.txid, this.vout, this.status, this.value});

  factory UtxoObject.fromJson(Map<String, dynamic> json) {
    return UtxoObject(
      txid: json['txid'],
      vout: json['vout'],
      status: Status.fromJson(json['status']),
      value: json['value']
    );
  }
}

class Status {
  final bool confirmed;
  final String blockHash;
  final int blockHeight;
  final int blockTime;

  Status({this.confirmed, this.blockHash, this.blockHeight, this.blockTime});

  factory Status.fromJson(Map<String, dynamic> json) {
    return Status(
      confirmed: json['confirmed'],
      blockHash: json['block_hash'],
      blockHeight: json['block_height'],
      blockTime: json['block_time']
    );
  }

}

这是在代码中实际调用API的函数:
Future<UtxoData> fetchUtxoData() async {
    final requestBody = {
      "currency": "USD",
      "receivingAddresses": ["bc1q5jf6r77vhdd4t54xmzgls823g80pz9d9k73d2r"],
      "internalAndChangeAddressArray": ["bc1q5jf6r77vhdd4t54xmzgls823g80pz9d9k73d2r"]
    };

    final response = await http.post('https://thisisanexmapleapiurl.com', body: jsonEncode(requestBody), headers: {'Content-Type': 'application/json'} );

    if (response.statusCode == 200 || response.statusCode == 201) {
      notifyListeners();
      print(response.body);
      return UtxoData.fromJson(json.decode(response.body));
    } else {
      throw Exception('Something happened: ' + response.statusCode.toString() + response.body );
    }
  }

但是,当我运行该函数时,在编辑器中出现以下错误:
Exception has occurred.
_TypeError (type 'int' is not a subtype of type 'double')

我在UtxoData类的工厂方法内的return UtxoData语句中得到它,如下所示:
return UtxoData(
      totalUserCurrency: json['total_user_currency'],
      satoshiBalance: json['total_sats'],                    <<<<============= The exception pops up right there for some reason
      bitcoinBalance: json['total_btc'],
      unspentOutputArray: utxoList
    );

这很奇怪,因为我知道API在那里返回一个int。 totalUserCurrency和bitcoinBalance必须是动态的,因为它们可以为0(整数)或任意数字,如12942.3232( double )。

为什么会出现此错误,我该如何纠正?非常感激

最佳答案

我有一个类似的问题,我从API获得的金额介于0到几千之间(包括小数)。我尝试了以下方法:

this.balanceAmount = double.parse(json['total_balance']??'0.0'.toString());

这不适用于我的数据集。因此,我将其增强为以下情况,该情况适用于我的数据集的所有情况。您可能需要稍微的增强。
double parseAmount(dynamic dAmount){

    double returnAmount = 0.00;
    String strAmount;

    try {

      if (dAmount == null || dAmount == 0) return 0.0;

      strAmount = dAmount.toString();

      if (strAmount.contains('.')) {
        returnAmount = double.parse(strAmount);
      }  // Didn't need else since the input was either 0, an integer or a double
    } catch (e) {
      return 0.000;
    }

    return returnAmount;
  }

关于json - 'int'类型不是 'double'类型的子类型— Dart/flutter 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61398215/

相关文章:

flutter - Tabbar抖动中的向后处理按钮

css - 使用 KO 将天气 id 值数据绑定(bind)到 mvc razor View 中的 i 类

mysql - 按年分组、按月/年分组

node.js - 是否不可能改变 Mongoose 查询返回的对象?

Flutter Socket-Io 没有连接到服务器?

dart - getter 中的 future 对象

php - MySQL位数据类型php打印unicode怎么来的?

dart - 如何使用 BottomAppBar 在 flutter 中进行导航

android - Flutter Web 在现有 Flutter 应用程序中创建问题

angular - ng如果无法立即使用(Angular Dart)