Flutter: Issue while converting json to model using json_serializable

2k views Asked by At

Suppose there are two models User and City

@JsonSerializable()
class User {
    int id;
    String name;
    City? city;
}

@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 as null.

Any help or solution would be really appreciated, Thank you

1

There are 1 answers

4
Abdur Rafay Saleem On

There is currently no support for ignoring a certain field only while serializing or only while deserializing. You can either ignore both or none. However, there is a workaround that I use.

  1. Make a global method in your model file that just returns null like this:
T? toNull<T>(_) => null;
  1. Inside your User model add a custom JsonKey for City:
@JsonKey(fromJson: toNull, includeIfNull: false)
City? City;

What this does is when converting from Json it uses your specificed function for converting city and replaces your value with null. Then due to includeIfNull property it just skips parsing.