json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

Not parse response when data is empty for a key

Open garg204 opened this issue 2 years ago • 1 comments

Hey, I have a model like this, in this scenario in failure case my data can be empty and there will be an error in response. Something like this. But on Message model it is failing as keys are not empty in that mode. How we can handle this case?

{
  "data": {
  },
  "success": false,
  "errors": [
    {
  
    }
  ]
}
@JsonSerializable()
class MessageResponse {
  factory MessageResponse.fromJson(Map<String, dynamic> json) =>
      _$MessageResponseFromJson(json);

  Map<String, dynamic> toJson() => _$MessageResponseToJson(this);

  @JsonKey(name: "data")
  late Message data;
  @JsonKey(name: "errors")
  late List<Map<String, dynamic>> errors;

  MessageResponse(
    this.data,
    this.success,
    this.errors,
  );
}
class Message {
  factory Message.fromJson(Map<String, dynamic> json) =>
      _$MessageFromJson(json);

  Map<String, dynamic> toJson() => _$MessageToJson(this);

  @JsonKey(name: "id")
  late String id;

}

garg204 avatar Apr 08 '22 09:04 garg204

How about adding a default value?

so, I don't think it will result in a null error.

ghost avatar Aug 30 '22 08:08 ghost

@Ryotaguchi0803 idea seems good here!

kevmoo avatar Oct 04 '22 02:10 kevmoo