'Flutter: json_serializable ignore nullable fields instead of throwing an error
Suppose there are two models User and City
@JsonSerializable()
class User {
int id;
String name;
City? city;
List<Map<String, City>>? listMapCity;
}
@JsonSerializable()
class City {
int id;
String name;
}
Now suppose during API call, we've got a user model but in the city object model, we only get id not name. Something like this
{
"id": 5,
"name": "Matthew",
"city": {
"id": 12
}
}
But due to the default nature of json_serializable and json_annotation.
This JSON is not mapped to the User model, during mapping, it throws the exception.
type Null is not a subtype of type String. (because here name key is missing in city object)
But as we already declared in the User object that City is optional, I wanted that it should parse the User JSON with city and listMapCity to be null.
Any help or solution would be really appreciated, Thank you
Solution 1:[1]
You need to have a default constructor on your JsonSerializable User
class. Then, if name
should be nullable, declare it with a nullable String? name;
Here's the updated User class.
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
int id;
String name;
City? city;
List<Map<String, City>>? listMapCity;
User({required this.id, required this.name, this.city, this.listMapCity});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
@JsonSerializable()
class City {
int id;
String name;
City({required this.id, required this.name});
}
Solution 2:[2]
You need to set the includeIfNull flag to false to have the autogenerated code handle nulls correctly.
@JsonSerializable(includeIfNull: false)
The property should be declared with a ? as per your example.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Omatt |
Solution 2 | sweetfa |