Last active
December 8, 2021 10:16
-
-
Save chonghorizons/450b502c4e5e666805be11423b1393a2 to your computer and use it in GitHub Desktop.
jsonEncode, extensions gotcha
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See https://stackoverflow.com/questions/70272959/jsonencode-doesnt-work-with-enum-extensions-is-there-a-workaround | |
import 'dart:convert'; | |
enum Day { monday, tuesday } | |
extension ParseToJsonString on Day { | |
String toJson() { | |
return this.toString().split('.').last; | |
} | |
} | |
class Saturday { | |
String toJson() => "WOOHOO Saturday"; | |
} | |
main() { | |
//works! | |
Saturday s = Saturday(); | |
print(s.toJson()); | |
print(jsonEncode(s)); | |
Day m = Day.monday; | |
print(m.toJson()); //prints 'monday' | |
print(m); //prints Day.Monday | |
// print(jsonEncode(m)); // Uncaught Error: Converting object to an encodable object failed: Instance of 'Day' | |
print('continues'); | |
print(jsonEncode( | |
m, | |
toEncodable: (x) { | |
Day recastX = x as Day; | |
return recastX.toJson(); | |
}, | |
)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment