I am trying to use the built-value package to serialize/deserialize data. But I am facing difficulty parsing nested JSON data using the above package. Please help where do I have to make changes, as most of the code is automatically generated by the build runner.
JSON INPUT:
{
"Italian": [
{
"name": "Item A",
"price": 297.0,
"stall": "380b80f4-425a-4916-b8ec-3a2ce0139d07",
},
{
"name": "Item B",
"price": 72.0,
"stall": "380b80f4-425a-4916-b8ec-3a2ce0139d07",
},
],
}
abstract class StallMenuItem
implements Built<StallMenuItem, StallMenuItemBuilder> {
@BuiltValueField(wireName: 'name')
String get itemName;
@BuiltValueField(wireName: 'price')
num get price;
@BuiltValueField(wireName: 'stall')
String get stallId;
StallMenuItem._();
factory StallMenuItem([updates(StallMenuItemBuilder b)]) = _$StallMenuItem;
static Serializer<StallMenuItem> get serializer => _$stallMenuItemSerializer;
}
abstract class StallMenuItemList
implements Built<StallMenuItemList, StallMenuItemListBuilder> {
BuiltMap<String, BuiltList<StallMenuItem>> get foodCategoryMap;
StallMenuItemList._();
factory StallMenuItemList([updates(StallMenuItemListBuilder b)]) =
_$StallMenuItemList;
static Serializer<StallMenuItemList> get serializer =>
_$stallMenuItemListSerializer;
}
class BuiltValueConvertor extends JsonConverter {
@override
Response<BodyType> convertResponse<BodyType, InnerType>(Response response) {
final Response dynamicResponse = super.convertResponse(response);
final BodyType customBody = _convertToCustomObject<InnerType>(dynamicResponse.body);
return dynamicResponse.replace<BodyType>(body: customBody);
}
dynamic _convertToCustomObject<InnerType>(dynamic element) {
if (element is InnerType) return element;
if (element is List)
return _deserializeListOf<InnerType>(element);
else
return _deserialize<InnerType>(element);
}
BuiltList<InnerType> _deserializeListOf<InnerType>(
List dynamicList,
) {
return BuiltList<InnerType>(
dynamicList.map((element) => _deserialize<InnerType>(element)),
);
}
InnerType _deserialize<InnerType>(
Map<String, dynamic> value,
) {
return serializers.deserializeWith<InnerType>(
serializers.serializerForType(InnerType),
value,
);
}
}
@SerializersFor(const [StallItem, StallMenuItem, StallMenuItemList, BuiltMap])
final Serializers serializers =
(_$serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();
I have followed the following tutorials:-https://resocoder.com/2019/07/14/chopper-retrofit-for-flutter-3-converters-built-value-integration/
E/flutter (31674): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'BuiltMapSerializer' is not a subtype of type 'Serializer<BuiltMap<String, BuiltList<StallMenuItem>>>'
Kindly use this code.