Skip to content

how to set default value to nested JSON objects? #789

Closed
@Qwampa

Description

@Qwampa

I am trying to figure out how to properly set the default value to nested JSON fields.
I am trying to avoid null values for missing fields in the response json.

I have tried this:

@JsonSerializable(explicitToJson: true)
class LoginResponse {
  @JsonKey(defaultValue: false)
  bool success;
  @JsonKey(defaultValue: new UserDataModel())
  UserDataModel seeker;
  @JsonKey(defaultValue: 0)
  int timestamp;

but the syntax is not correct as the value must be a constant.

I have also tried this:

@JsonSerializable(explicitToJson: true)
class LoginResponse {
  @JsonKey(defaultValue: false)
  bool success;
  @JsonKey(disallowNullValue: true, defaultValue: {"seeker": {"id": "", "name": "", "email": "",}})
  UserDataModel seeker;
  @JsonKey(defaultValue: 0)
  int timestamp;
  

Generated code:

LoginResponse _$LoginResponseFromJson(Map<String, dynamic> json) {
$checkKeys(json, disallowNullValues: const ['seeker']);
return LoginResponse(
  success: json['success'] as bool ?? false,
  seeker: json['seeker'] == null
      ? null
      : UserDataModel.fromJson(json['seeker'] as Map<String, dynamic>) ??
          {
            'seeker': {
              'id': '',
              'name': '',
              'email': ''
            }
          },
  timestamp: json['timestamp'] as int ?? 0,
);
}

but when the response does not include the field, it is still set to null.
Any help would be appreciated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions