Dart Error Converting Object To JSON

元气小坏坏 提交于 2019-12-21 20:52:23

问题


I'm getting the following error:

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<…>

My 'Patient' class:

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);
  }

}

回答1:


You can't just convert any arbitrary class instance to JSON

The class needs to implement toEncodable

https://api.dartlang.org/stable/1.24.3/dart-convert/JsonEncoder-class.html

https://pub.dartlang.org/packages/json_serializable is a package that generates code for that so that you don't need to write it manually.

See also https://flutter.io/json/




回答2:


In my case, I was attempting to use an integer key in a map object. Once I converted it to String, the error was resolved. Good luck.



来源:https://stackoverflow.com/questions/49753412/dart-error-converting-object-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!