google / json_serializable.dart

Generates utilities to aid in serializing to/from JSON.
https://pub.dev/packages/json_serializable
BSD 3-Clause "New" or "Revised" License
1.55k stars 395 forks source link

Future data serialisation #1306

Closed HeropolisDa2ny closed 1 month ago

HeropolisDa2ny commented 1 year ago

Hello,

I am working with an online/offline app and I need to serialise my data at the app start up. So I have to do a trick with my images. I collect the bytes directly from the server at the data serialisation.

So here I am trying to use this converting function using a Future return type :

static Future<Uint8List>? urlToImageBytes(String url) async => http.readBytes(Uri.parse(url));

So I need to put it in the JsonKey, however fromJson doesn't accept Future.

@JsonKey(fromJson: urlToImageBytes)
final Uint8List? value;

Any idea to fix it ?

Here my versions if need :

Dart SDK version: 2.19.5 (stable) on "macos_arm64"
Flutter 3.7.8 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 90c64ed42b (4 weeks ago)
Engine • revision 9aa7816315
Tools • Dart 2.19.5 • DevTools 2.20.1
TimWhiting commented 1 year ago

You should probably just do:

class YourClass {
  final String url;
  static Future<Uint8List>? urlToImageBytes(String url) async => http.readBytes(Uri.parse(url));
  late final Uint8List? value => urlToImageBytes(url);
}
HeropolisDa2ny commented 1 year ago

This is a potential solution for formatting the image after the serialisation but not while serialising. So this is not what I would like. I also could re-write my json['value'] with the transformed image but I also do not want that solution because it doesn't fix properly the problem.

Here the main problem is that the fromJson is made of a factory, so it cannot use async methods inside, that's why JsonKey(fromJson doesn't expect us to provide an async method.

I was asking myself why using a factory here instead of a static method returning its instance ? This could allow the usage of async methods into a fromJson. However I don't know if it is a proper solution and would requires to make a PR.