Would like a way to specify a type supports toJson and fromJson #53758
Labels
area-core-library
SDK core library issues (core, async, ...); use area-vm or area-web for platform specific libraries.
library-convert
type-enhancement
A request for a change that isn't a bug
Would like a way to specify a type supports toJson and fromJson
Maybe this is related to #34415 or #35693?
Specifying a type supports toJson or fromJson may also be separate bugs. Say you wanted to offer an generic storage class which used json as the storage medium.
One such example from code I've written:
https://github.com/eseidel/space_traders/blob/8fc555e6d5e9c7a3749a3d5e9ca41de55ce9a4ff/packages/cli/lib/cache/json_store.dart
https://github.com/eseidel/space_traders/blob/8fc555e6d5e9c7a3749a3d5e9ca41de55ce9a4ff/packages/cli/lib/cache/json_list_store.dart
e.g.
You have no way to specify that T supports toJson and fromJson (again, possibly separate problems). The best workaround I know of is to have all subclasses pass down toJson and fromJson functions to the superclass, e.g.
(Yes, maybe those signature are supposed to take/return dynamic instead of Map<String, dynamic>.)
You could work-around the toJson case, by casting T to dynamic and calling toJson on dynamic? (I think that would work?)
But I know of no way to work around passing fromJson since that's typically a factory method.
In C++ you might handle this by having a separate Traits definition that you instantiated within your superclass to provide extra metadata (including toJson/fromJson functions) for T.
In Rust, you could restrict the type T to only those having a Trait "JsonSerializable" or similar. I don't think such is possible in Dart?
The text was updated successfully, but these errors were encountered: