json_serializable.dart
json_serializable.dart copied to clipboard
Allow non-String map keys, if there exists a compatible converter
Map<Version, int>
should be doable...
Or Map<int, int>
for that matter.
I'd really like to be able to use value objects in place of String
s to make my Map
s a bit more clear. When this feature is complete will I be able to do something like the following?
@JsonSerializable()
class ContainerThing {
Map<ThingId, int> stuff;
}
class ThingId extends StringValue {
ThingId(String value) : super(value);
}
class StringValue extends Value<String> {
StringValue(String value) : super(value);
}
class StringValueConverter implements JsonConverter<StringValue, String> {
@override
StringValue fromJson(String json) => StringValue(json);
@override
String toJson(StringValue object) => object.value;
}
@immutable
abstract class Value<T> {
final T value;
Value(this.value);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Value &&
runtimeType == other.runtimeType &&
value == other.value;
@override
int get hashCode => value.hashCode;
}
@bgetsug – right now, no. I've wired through support for known types.
Getting this generic for an arbitrary key type will be...interesting. 😄 I think I can pull it off, though.
Any update on this feature?
Nope. Prs welcome!
The basics seems to work for regular maps (Map<int, int>), but not for maps that implement their own toJsonK / toJsonV / fromJsonK / fromJsonV converters such as IMap<int, int> from the fast_immutable_collections package. For that sort of use case, a @jsonKeyType
annotation on the toJsonK and fromJsonK could be a good API, or even directly on the K
type in the generic class. I tried looking into implementing this but got stuck.