3

Does anyone know how can I serialize/deserialize a Map<String, dynamic> instead of String that is the default in the toJson e fromJson methods of the built_value package?

I need to use Firestore and the setData method only accepts a Map for the data.

My current Serializer class has the code below. There's some other plugin or config that I can add to work with the map?

final Serializers serializers =
    (_$serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();

Here are the methods:

 String toJson() {
    return json.encode(serializers.serializeWith(Comment.serializer, this));
  }

  static Comment fromJson(String jsonString) {
    return serializers.deserializeWith(
        Comment.serializer, json.decode(jsonString));
  }
JRamos29
  • 880
  • 7
  • 20

1 Answers1

2

Your toJson method should look like:

  Map<String, dynamic> toJson() {
    return serializers.serializeWith(PlayerModel.serializer, this);
  }

That is get rid of the json.encode.

Similarly for fromJson:

  static PlayerModel fromJson(Map<String, dynamic> json) {
    return serializers.deserializeWith(PlayerModel.serializer, json);
  }

Here is a sample PlayerModel I use:

abstract class PlayerModel implements Built<PlayerModel, PlayerModelBuilder> {
  @nullable
  String get uid;
  String get displayName;

  PlayerModel._();
  factory PlayerModel([void Function(PlayerModelBuilder) updates]) =
      _$PlayerModel;

  Map<String, dynamic> toJson() {
    return serializers.serializeWith(PlayerModel.serializer, this);
  }

  static PlayerModel fromJson(Map<String, dynamic> json) {
    return serializers.deserializeWith(PlayerModel.serializer, json);
  }

  static Serializer<PlayerModel> get serializer => _$playerModelSerializer;
}
ravish.hacker
  • 1,189
  • 14
  • 21
  • I'm having the following error when applying your solution: `A value of type 'Object?' can't be returned from the method 'toJson' because it has a return type of 'Map'.` Any idea why? – Binajmen May 28 '21 at 14:27
  • 1
    I've descibed my issue there: https://stackoverflow.com/questions/67742383/error-while-serializing-builtobject-using-built-value-combined-with-flutterfir – Binajmen May 28 '21 at 16:22