gpt4 book ai didi

json - 如何在 Flutter 中将对象编码为 json

转载 作者:IT王子 更新时间:2023-10-29 06:39:26 25 4
gpt4 key购买 nike

我正在尝试将对象“Week”转换为 json。

https://flutter.dev/docs/development/data-and-backend/json这是我使用的来源

class Week{
DateTime _startDate;
DateTime _endDate;
List<Goal> _goalList;
String _improvement;

Week(this._startDate, this._endDate){
this._goalList = List<Goal>();
this._improvement = "";
}

Week.fromJson(Map<String, dynamic> json)
: _startDate = json['startDate'],
_endDate = json['endDate'],
_goalList = json['goalList'],
_improvement = json['improvement'];

Map<String, dynamic> toJson() =>
{
'startDate': _startDate,
'endDate': _endDate,
'goalList': _goalList,
'improvement': _improvement,
};
}

我用过这个:

DateTime startDate = currentDate.subtract(new Duration(days:(weekday-1)));
DateTime endDate = currentDate.add(new Duration(days:(7-weekday)));

Week week = new Week(startDate, endDate);
var json = jsonEncode(week);

但问题是我得到了这个结果:

Unhandled Exception: Converting object to an encodable object failed: Instance of 'Week'
#0 _JsonStringifier.writeObject (dart:convert/json.dart:647:7)
#1 _JsonStringStringifier.printOn (dart:convert/json.dart:834:17)
#2 _JsonStringStringifier.stringify (dart:convert/json.dart:819:5)
#3 JsonEncoder.convert (dart:convert/json.dart:255:30)
#4 JsonCodec.encode (dart:convert/json.dart:166:45)
#5 jsonEncode (dart:convert/json.dart:80:10)

最佳答案

jsonEncode 需要 Map<String, dynamic> , 不是 Week目的。调用你的 toJson()方法应该可以解决问题。

var json = jsonEncode(week.toJson());

但是,请记住您的 toJson()方法也不正确,因为 _goalList 和日期之类的东西仍然是对象,而不是 map 或列表。您还需要对它们实现 toJson 方法。

回答您的具体问题:

  1. 因为 dart 不是 javascript/typescript。 Dart 在运行时检查类型,因此你必须明确地告诉它如何转换东西——而且 dart 中没有反射,所以它不能自己弄清楚。
  2. 您可以使用一个使用代码生成的库来自动为您完成这些事情——尽管它在运行时仍然不可能——阅读更多关于 JSON serialization 的信息.
  3. 最简单的方法是直接在类中实现方法,因为这是您可以在根对象中访问的地方。请记住 jsonEncode 的结构需要的是一个Map<String, dynamic> ,但是 dynamic部分真正意味着 List<dynamic> , Map<String, dynamic>或与 json 兼容的原语,例如 Stringdouble - 如果您尝试想象上述类型的这种嵌套结构的外观,您会发现它基本上是 json。所以当你做类似 'goalList': _goalList, 的事情时你给它一个对象,这不是允许的类型之一。

希望这能让事情变得更清楚一些。

关于json - 如何在 Flutter 中将对象编码为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56406601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com