gpt4 book ai didi

json - 将对象转换为可编码对象失败

转载 作者:行者123 更新时间:2023-12-03 02:38:49 27 4
gpt4 key购买 nike

我收到以下错误:

Converting object to an encodable object failed: Instance of 'Patient'
#0 _JsonStringifier.writeObject (dart:convert/json.dart:674)
#1 _JsonStringifier.writeList (dart:convert/json.dart:724)
#2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:706)
#3 _JsonStringifier.writeObject (dart:convert/json.dart:664)
#4 _JsonStringStringifier.printOn (dart:convert/json.dart:873)
#5 _JsonStringStringifier.stringify (dart:convert/json.dart:855)
#6 JsonEncoder.convert (dart:convert/json.dart:256)
#7 JsonCodec.encode (dart:convert/json.dart:155)
#8 Persistence.saveLatestPatients (/Users/dean/Library/Developer/CoreSimulator/Devices/570CC18D-95BF-4062-8523-9C78E106D0CF/data/Containers/Data/Application/70CAEFAA-4AE3-4CBF-A85F-39161E472C83/tmp/flutter_prototypev6jYbr/flutter_prototype/lib/utils/persistence.dart:32:23)
<asynchronous suspension>
#9 _HomeScreenState.fetchData.<anonymous closure> (/Users/dean/Librar<…>

我的“病人”课:
import 'package:simple_moment/simple_moment.dart';

class Patient {
String guid;
String _name;
String _surname;
DateTime _updated;

Patient(String guid) {
this.guid = guid;
}

String get name => _name;
set name(v) => _name = v;

String get surname => _surname;
set surname(v) => _surname = v;

DateTime get updated => _updated;
set updated(v) => _updated = v;

// Helper functions

String getFullName() => '$_name $_surname';

String getRelativeLastUpdated() {
var moment = new Moment.now();
return moment.from(_updated);
}

}

最佳答案

您不能只是将任意类实例转换为 JSON。
一种选择是为 JsonEncoder() 构造函数提供自定义函数(通过 toEncodable 参数)。这个自定义函数应该将您的自定义对象映射到 JsonEncoder 已经知道如何处理的类型(即数字、字符串、 bool 值、空值、列表和带有字符串键的映射)。
https://api.dartlang.org/stable/1.24.3/dart-convert/JsonEncoder-class.html
https://pub.dartlang.org/packages/json_serializable是一个为此生成代码的包,因此您无需手动编写它。
另见 https://flutter.io/json/

关于json - 将对象转换为可编码对象失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49753412/

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