marcglasberg / fast_immutable_collections

Dart Package: Immutable lists, sets, maps, and multimaps, which are as fast as their native mutable counterparts. Extension methods and comparators for native Dart collections.
BSD 2-Clause "Simplified" License
217 stars 30 forks source link

IMap.fromJson does not support custom types for keys #82

Open urusai88 opened 1 month ago

urusai88 commented 1 month ago
map_point.dart
import 'dart:math';

typedef MapPoint = Point<int>;

class MapPointJsonConverter extends JsonConverter<MapPoint, String> {
  const MapPointJsonConverter();

  @override
  MapPoint fromJson(String json) => parseMapPoint(json);

  @override
  String toJson(MapPoint object) => '${object.x}x${object.y}';
}
entity.dart
import 'package:json_serializable/json_serializable.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';

part 'entity.g.dart';

@JsonSerializable(converters: [MapPointJsonConverter()])
class Entity {
  const Entity({required this.map});

  factory Entity.fromJson(Map<String, dynamic> json) => _$EntityFromJson(json);

  final IMap<MapPoint, int> map;
}
entity.g.dart
Entity _$EntityFromJson(Map<String, dynamic> json) =>
    Entity(
      map: json['map'] == null
          ? const IMap.empty()
          : IMap<Point<int>, int>.fromJson(
              json['map'] as Map<String, dynamic>,
              (value) =>
                  const MapPointJsonConverter().fromJson(value as String),
              (value) => (value as num).toInt(),
    );
error
Unhandled Exception: Unsupported operation: 
JSON deserialization of IMap keys of type Point<int> are not supported at the moment.
stack trace
#0 _safeKeyFromJson (package:fast_immutable_collections/src/imap/imap.dart:1558:5)
#1 new IMap.fromJson.<anonymous closure> (package:fast_immutable_collections/src/imap/imap.dart:498:50)
#2 MapBase.map (dart:collection/maps.dart:82:28)
#3 new IMap.fromJson (package:fast_immutable_collections/src/imap/imap.dart:497:12)
marcglasberg commented 1 month ago

Related to:

https://github.com/marcglasberg/fast_immutable_collections/issues/39 https://github.com/marcglasberg/fast_immutable_collections/issues/58