英文:
jsonEncode generating error while converting object to jsonstring in flutter
问题
以下是要翻译的内容:
For explaining what I am facing problem while creating a jsonstring from object list, I have created this basic demo, actually I am trying to create a backup file for saving records but I am getting an error while jsonEncode.
getting following error
Converting object to an encodable object failed: Instance of 'TransactionModel'
String id;
bool isexpense;
DateTime date;
double amount;
TransactionModel({
this.amount = 0.00,
required this.id,
this.isexpense = true,
required this date,
});
Map<String, dynamic> toJson() {
return {
'id': id,
'isexpense': isexpense,
'date': date,
'amount': amount,
};
}
}
List<TransactionModel> trans = [
TransactionModel(
date: DateTime.now(),
id: '1',),
];
String result = jsonEncode(trans);//error bcz of jsonEncode
print(result);
}
英文:
For explaining what I am facing problem while creating a jsonstring from object list,I have created this basic demo,
actually I am trying to create a backup file for saving records but I am getting an error while jsonEncode.
getting following error
Converting object to an encodable object failed: Instance of 'TransactionModel'
class TransactionModel {
String id;
bool isexpense;
DateTime date;
double amount;
TransactionModel({
this.amount = 0.00,
required this.id,
this.isexpense = true,
required this.date,
});
Map<String, dynamic> toJson() {
return {
'id': id,
'isexpense': isexpense,
'date': date,
'amount': amount,
};
}
}
void main() {
List<TransactionModel> trans = [
TransactionModel(
date: DateTime.now(),
id: '1',),
];
String result = jsonEncode(trans);//error bcz of jsonEncode
print(result);
}
答案1
得分: 1
以下是翻译好的部分:
"你不能使用自定义属性(例如DateTime
)对一个object
进行编码,你需要首先将它转换为map
,然后再进行编码,试试这样做:
void main() {
List<TransactionModel> trans = [
TransactionModel(
date: DateTime.now(),
id: '1',
),
];
var listOfMap = trans.map((e) => e.toJson()).toList();
String result = jsonEncode(listOfMap);
print(result);
}
```"
<details>
<summary>英文:</summary>
You can't encode an `object` with custom property like `DateTime`, you need first convert it to `map`, then encode it, try this:
void main() {
List<TransactionModel> trans = [
TransactionModel(
date: DateTime.now(),
id: '1',),
];
var listOfMap = trans.map((e) => e.toJson()).toList();
String result = jsonEncode(listOfMap);
print(result);
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论