json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

Allow non-String map keys, if there exists a compatible converter

Open kevmoo opened this issue 5 years ago • 6 comments

Map<Version, int> should be doable...

kevmoo avatar Feb 26 '19 19:02 kevmoo

Or Map<int, int> for that matter.

kevmoo avatar Apr 02 '19 16:04 kevmoo

I'd really like to be able to use value objects in place of Strings to make my Maps 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 avatar Jul 08 '19 03:07 bgetsug

@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.

kevmoo avatar Jul 08 '19 17:07 kevmoo

Any update on this feature?

sterlingwellscaffeine avatar Sep 08 '21 15:09 sterlingwellscaffeine

Nope. Prs welcome!

kevmoo avatar Sep 08 '21 16:09 kevmoo

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.

TimWhiting avatar Sep 29 '21 18:09 TimWhiting