Below is my JSON that i am getting in api response. I want to parse below json in flutter dart using json_serializable.
[
{
"id": 1,
"email": "[email protected]",
"gender": "Female",
"ip_address": "101.34.28.146",
"name": "Gerry",
"retro": true
},
{
"id": 2,
"email": "[email protected]",
"gender": "Male",
"ip_address": "117.77.75.29",
"name": "Zared",
"retro": ""
},
{
"id": 3,
"email": "[email protected]",
"gender": "Male",
"ip_address": "165.84.97.206",
"name": "Ozzy",
"retro": true
},
{
"id": 4,
"email": "[email protected]",
"gender": "Male",
"ip_address": "76.73.136.113",
"name": "Edwin",
"retro": false
}
]
Below is my object class form json
import 'package:json_annotation/json_annotation.dart';
@JsonSerializable()
class UserItem {
int id;
String email;
String gender;
@JsonKey(name: 'ip_address')
String ipAddress;
String name;
bool retro;
UserItem(this.id, this.email, this.gender, this.ipAddress, this.name, this.retro);
factory UserItem.fromJson(Map<String, dynamic> json) => _$UserItemFromJson(json);
Map<String, dynamic> toJson() => _$UserItemToJson(this);
}
UserItem _$UserItemFromJson(Map<String, dynamic> json) => UserItem(
json['id'] as int,
json['email'] as String,
json['gender'] as String,
json['ip_address'] as String,
json['name'] as String,
json['retro'] as bool,
);
Map<String, dynamic> _$UserItemToJson(UserItem instance) => <String, dynamic>{
'id': instance.id,
'email': instance.email,
'gender': instance.gender,
'ip_address': instance.ipAddress,
'name': instance.name,
'retro': instance.retro,
};
I am unable to parse json because object at id:3 contains retro:"" and in rest of json retro is bool type. i am getting Type Cast Exception
jsonParse exception: type 'String' is not a subtype of type 'bool' in type cast
NOTE: I am using third party API solution and i am unable to ask for changes on api response to change empty string in json response with default boolean value.
Instead of
You can do
That way you can support both bool and string type.