Reputation: 890
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));
}
Upvotes: 3
Views: 1433
Reputation: 1183
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;
}
Upvotes: 2