Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode an object to json in Flutter

Tags:

json

flutter

dart

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) 
like image 762
laaasBIGL Avatar asked Jun 01 '19 12:06

laaasBIGL


People also ask

How do I encode a JSON flutter?

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.

Why we use JSON encode in flutter?

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.


1 Answers

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:

  1. Because dart is not javascript / typescript. Dart checks types at runtime, therefore you have to explicitly tell it how to convert things - also there is no reflection in dart, so it can't figure it out by itself.
  2. You can use a library that uses code generation to do these things automatically for you - it still wont be possible at runtime though - read more about JSON serialization.
  3. The easiest way would be to implement the methods directly in the classes, as that's where you have access to in your root object. Keep in mind that the structure that 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.

like image 184
Philip Feldmann Avatar answered Sep 22 '22 14:09

Philip Feldmann