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

Support a CustomMap

Open JoanSchi opened this issue 9 months ago • 1 comments

Support for the serialization of a custom map, with the same key Type support as map is missing.

At the moment we use the implementation from the tuple_example to convert a custom Map to json and back (IMap in fast_immutable_collections) In the tuple example we use toJsonT for the key Type conversion, however for example an integer is returned as a integer and not as a String, which makes sense for a value in a tuple, but not for a key in a json map.

A similar implementation of the tuple_example but with support for a key conversion toJsonK with the same Type support as Map, would be great.

class CustomMap<K, V> {
  Map<K, V> dummy;
  CustomMap(
    this.dummy,
  );

  factory CustomMap.fromJson(
    Map<String, dynamic> json,
    K Function(String) fromJsonK,
    V Function(Object?) fromJsonV,
  ) =>
      CustomMap(json.map<K, V>(
          (key, value) => MapEntry(fromJsonK(key), fromJsonV(value))));

  Map<String, dynamic> toJson(
          String Function(K) toJsonK, Object? Function(V) toJsonV) =>
      dummy.map((key, value) => MapEntry(toJsonK(key), toJsonV(value)));
}

JoanSchi avatar Feb 27 '25 09:02 JoanSchi

Oh wow. That's tricky. We'd need to support logic to auto-convert certain type arguments to String.

kevmoo avatar Mar 20 '25 18:03 kevmoo