我正在尝试将build_value和json_serializable一起用于解析从服务器到模型类的json响应。
以下是依赖项:
built_collection: ^4.0.0
built_value: ^6.1.4
dev_dependencies:
build_runner: ^1.0.0
built_value_generator: ^6.1.4
json_serializable: ^1.4.0
以下是我编写的代码
abstract class UserData implements Built<UserData, UserDataBuilder>{
String get user_first_name;
String get user_last_name;
String get user_mobile;
String get email;
String get user_type;
Company get company;
UserType get type;
UserData._();
factory UserData([updates(UserDataBuilder b)]) = _$UserData;
static Serializer<UserData> get serializer => _$userDataSerializer;
}
abstract class Company implements Built<Company, CompanyBuilder>{
String get id;
Company._();
factory Company([updates(CompanyBuilder b)]) = _$Company;
static Serializer<Company> get serializer => _$companySerializer;
}
abstract class UserType implements Built<UserType, UserTypeBuilder>{
String get id;
UserType._();
factory UserType([updates(UserTypeBuilder b)]) = _$UserType;
static Serializer<UserType> get serializer => _$userTypeSerializer;
}
序列化器类代码:
@SerializersFor(const [
UserData
])
Serializers serializers = _$serializers;
Serializers standardSerializers =
(serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();
以下是我从服务器获得的响应。
{
"user": {
"id": "505d27b0-acaa-11e8-b916-21359608417b",
"email": "example@gmail.com",
"user_first_name": "Pankaj",
"user_last_name": "P",
"user_dob": null,
"active_status": 1,
"user_region_id": null,
"user_base_currency": "USD",
"user_address": null,
"is_god_user": 0,
"is_super_user": 0,
"profile": null,
"advanced_search": 0,
"region": null,
"company": {
"id": "24e311f0-acaa-11e8-8750-8de299c7797b",
"company_name": "SHPR A",
"company_address": null,
"company_logo": "",
"company_constitution": "pvt_ltd",
"company_email": "shpra@mail.com",
"state": null,
"country": null,
"postal_code": null,
"date_of_establishment": null,
"number_of_employees": null,
"company_turnover": null,
"vendor_id": null
},
"type": {
"id": "5eeebe55-fdf4-11e7-81f1-ac7ba173bed6",
"user_type_code": "11",
"user_type_name": "ADMIN",
"user_category": "SHIPPER"
}
}
}
最后,我尝试使用以下代码行进行解析
serializers.deserializeWith(UserData.serializer, json.decode(response.body))
但是我遇到以下错误
failed due to: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>' in type cast
请阐明可能导致此问题的原因。
答案 0 :(得分:1)
堆栈跟踪可以告诉您错误在哪里,所以如果有错误,它可能会很有用。
有时,您正在将Map<String, dynamic>
值分配给类型为Iterable<dynamic>
的变量。这听起来像JSON解码出错,有些事情是假设列表并获取地图。
提供的代码中没有假设Iterable<dynamic>
的内容,因此在json_serializable
包中最有可能爆炸的事情。
因此,您确定您拥有的JSON输入文本是json_serializable
解码器的正确格式吗? (我不熟悉该程序包,因此只能猜测)。
答案 1 :(得分:0)
我也遇到了同样的问题,替换
serializers.deserializeWith(UserData.serializer, json.decode(response.body))
使用
standardSerializers.deserializeWith(UserData.serializer, json.decode(response.body))