Search code examples
jsonflutterdartdeserialization

How to deserialize JSON when the result returns different data type


I have an issue with my JSON result.

When my JSON response is not empty is returning a dictionary:

{
    "data": {},
    "errors": [],
    "memId": 0
}

When the JSON is empty is returning an empty array:

[ ]

How can I deal with this situation when I try to deserialize the JSON response ?

Here is my code:

factory MyJsonObject.fromJson(Map<String, dynamic> json) =>
  MyJsonObject(
    data: json["data"] == null ? null : Data.fromJson(json["data"]),
    errors: json["errors"] == null ? [] : List<dynamic>.from(json["errors"]!.map((x) => x)),
    memId: json["memId"],
);

Solution

  • Make param as dynamic and add type check:

    factory MyJsonObject.fromJson(dynamic json) {
      if (json is Map<String, dynamic>) {
        return MyJsonObject(
          data: json["data"] == null ? null : Data.fromJson(json["data"]),
          errors: json["errors"] == null ? [] : 
          List<dynamic>.from(json["errors"]!.map((x) => x)),
          memId: json["memId"],
        );
      }
      return MyJsonObject.empty();
    }