Flutter: json_serializable ignore nullable fields instead of throwing an error

1,650

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});
}
Share:
1,650
Himanshu Arora
Author by

Himanshu Arora

Updated on December 02, 2022

Comments

  • Himanshu Arora
    Himanshu Arora over 1 year

    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