首页 > 解决方案 > Dart fromJson 无法解析双精度值

问题描述

我在颤振中使用 fromJson 时遇到问题。我收到这样的数据

{id: d7ba912e-69fd-11ea-9ab0-6597c4120b03, receipt_date: 2020-03-18T17:30:00.000Z, customer_id: e3fedf5e, amount: 2500, remark: Amount 2500, created_on: 2020-03-19T16:22:35.000Z, collectionSize: 3, name: Customer 1}

我正在使用这个 fromJson 来解析:

factory CashReceipt.fromJson(Map<String, dynamic> json) { return CashReceipt( id: json['id'], customerId: json['customer_id'], date: json['date'] as DateTime, amount: json['amount'] as double, remark: json['remark']); }

“金额”属性在我的模型中是双倍的。它导致以下错误。来自 API 的数据是“金额:2500”。如果我将“数量”更改为“int”,它就会消失。但这是不对的。非常感谢您的帮助。

_CastError (type 'int' is not a subtype of type 'double' in type cast)

标签: dartfromjson

解决方案


您可以使用

num amount

代替

double amount

你不会得到这个错误。看到这个文档


推荐阅读