Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

json - Converting object to an encodable object failed

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

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need to add any libraries. You just have to implement fromJson and toJson functions in your object.

Example:

class LinkItem {
  final String name;
  final String url;

  LinkItem({this.name, this.url});

  LinkItem.fromJson(Map<String, dynamic> json)
      : name = json['n'],
        url = json['u'];

  Map<String, dynamic> toJson() {
    return {
      'n': name,
      'u': url,
    };
  }
}

Then you can call jsonEncode:

List<LinkItem> list = await getUserLinks();
list.add(linkItem);    
String json = jsonEncode(list);

Result:

  [{"n":"Google","u":"https://www.google.com/"},{"n":"Test","u":"https://www.test.com/"},{"n":"etc","u":"etc"}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...