I have an API which sends me a type :
type Response = {
id: string;
values: Stringified<number[]>, // string
}
where type Stringified<T> = string; and is what you would get by using jsonEncode.
I want to create a Built class that matches the response architecture. This is what I have for now:
@SerializersFor([
MyResponse,
])
final Serializers _serializers = (_$_serializers.toBuilder()
..addPlugin(StandardJsonPlugin())
.build();
abstract class MyResponse implements Built<MyResponse, MyResponseBuilder> {
factory MyResponse([void Function(MyResponseBuilder) updates]) = _$MyResponse;
MyResponse._();
Map<String, dynamic> toJson() {
return _serializers.serializeWith(MyResponse.serializer, this)! as Map<String, dynamic>;
}
static MyResponse fromJson(Map<String, dynamic> json) {
return _serializers.deserializeWith(MyResponse.serializer, json)!;
}
static Serializer<MyResponse> get serializer => _$myResponseSerializer;
String get id;
List<int> get values;
}
This would work if I was receiving/sending data like :
{ "id": "id", "values": [0, 1, 2] }
But the data I receive or need to send is:
{ "id": "id", "values": "[0, 1, 2]" }
How can I override the toJson / fromJson of values or how can I add a pipe/how so I can use jsonEncode/jsonDecode when exporting to/importing from a JSON?
In the end, I managed to do it with a
SerializerPlugin:Here is a more complete example with 2 models:
where type
Stringified<T> = string;and is what you would get by usingjsonEncode.I created those built value classes:
Notice the
class MyPlugin extends SerializerPlugininmodel_2.dart. I add this plugin to theModel2serializer.It
afterSerializethat appliesjsonEncodeto the serialized list of serialized model1beforeDeserializethat appliesjsonDecodeto the deserialized stringified list of serialized model1