Ilia Tikhomirov
Ilia Tikhomirov

Reputation: 599

Dart: Return null value if JSON doesn't fit the object definition

Let's say I have a data model defined as following:

class GymInfo {
  final String openDate;
  final String phoneNumber;
  final String state;
  final String clubRegion;
  final String email;
  final int hasKeypad;
  final int isPlatinum;
  final String linkClub;
  final int id;
  final int is24Hour;
  final String fullname;
  final String type;

  GymInfo({this.openDate, this.phoneNumber, this.state, this.clubRegion, this.email, this.hasKeypad, this.isPlatinum, this.linkClub, @required this.id, this.is24Hour, @required  this.fullname, this.type,});

  factory GymInfo.fromJson(Map<String, dynamic> json) {

    return GymInfo(
    openDate: json['openDate'], 
    phoneNumber: json["PhoneNumber"],
    state: json["state"],
    clubRegion: json["ClubRegion"],
    email: json['Email'],
    hasKeypad: json['hasKeypad'],
    isPlatinum: json['isPlatinum'],
    linkClub: json['link_club'],
    id: json['id'],
    is24Hour: json['is24Hour'],
    fullname: json['fullname'],
    type: json['type']);
  }
}

Whenever I pass a JSON map to the factory I want it to return null if the map doesn't have values for the required parameters. At the moment it returns an instance of GymInfo with null set to all parameters, which creates problems for testing. How do I make sure that initialiser fails and returns null.

Upvotes: 3

Views: 2236

Answers (2)

mezoni
mezoni

Reputation: 11218

It is much easier than you can imagine.
JSON format is a format without any logic. This means that you should have a possibility change the implementation of your JSON objects at any time without impacts.
In this case would be more correct to implement required logic in your own service object.

MyJsonObject getMyObject(Object source) {
  // ...
  var myObject = MyJsonObject.fromJson(json);
  if (myObject.someField == null) {
    return null;
  }

  return myObject;
}```

Upvotes: 0

diegoveloper
diegoveloper

Reputation: 103561

Just add a simple validation to ensure your required fields are not null.

  factory GymInfo.fromJson(Map<String, dynamic> json) {

    final fullnameValue = json['fullname'];
    final idValue = json['id'];

    if (fullNameValue == null || idValue == null){
      return null;
    }

    return GymInfo(
    openDate: json['openDate'], 
    phoneNumber: json["PhoneNumber"],
    state: json["state"],
    clubRegion: json["ClubRegion"],
    email: json['Email'],
    hasKeypad: json['hasKeypad'],
    isPlatinum: json['isPlatinum'],
    linkClub: json['link_club'],
    id: idValue,
    is24Hour: json['is24Hour'],
    fullname: fullnameValue,
    type: json['type']);
  }

Upvotes: 4

Related Questions