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?
2
Answers
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 SerializerPlugin
inmodel_2.dart
. I add this plugin to theModel2
serializer.It
afterSerialize
that appliesjsonEncode
to the serialized list of serialized model1beforeDeserialize
that appliesjsonDecode
to the deserialized stringified list of serialized model1Im not sure this fit to your need. I ussually modify my
toJson()
method by changet its value.for example: in my model I use
@JsonSerializable
which will generated defaulttoJson
.to customize some keys, i do like below:maybe you can use similar pattern.