I am trying to convert the object "Week" to json.
https://flutter.dev/docs/development/data-and-backend/json this is the source that i used
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, }; }
I used this:
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);
But the problem is that I get this result:
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)
To encode a user, pass the User object to the jsonEncode() function. You don't need to call the toJson() method, since jsonEncode() already does it for you. String json = jsonEncode(user); With this approach, the calling code doesn't have to worry about JSON serialization at all.
jsonEncode function Null safetyConverts object to a JSON string. If value contains objects that are not directly encodable to a JSON string (a value that is not a number, boolean, string, null, list or a map with string keys), the toEncodable function is used to convert it to an object that must be directly encodable.
jsonEncode requires a Map<String, dynamic>
, not a Week
object. Calling your toJson()
method should do the trick.
var json = jsonEncode(week.toJson());
However, keep in mind that your toJson()
method is also incorrect, as things like _goalList and the dates are still objects, not Maps or Lists. You'll need to implement toJson methods on those as well.
To answer your specific questions:
jsonEncode
needs is a Map<String, dynamic>
, but the dynamic
part really means List<dynamic>
, Map<String, dynamic>
or a primitive that is json compatible such as String
or double
- if you try to imagine how such a nested structure of said types looks, you'll realise that it's basically json. So when you do something like 'goalList': _goalList,
you're giving it an object, which is not one of the allowed types.Hope this clears things up a bit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With