0

Here's one jsonData.

{
'name' :'chris',
'age' : 52,
'gender' : M,
'hobby' :'piano',
'favoriteFood' :'burger'
}

Here are two Freezed models

@freezed
class DefaultModel with _$DefaultModel{
const factory DefaultModel({
  required String name,
  required int age,
  required Gender gender,
}) =_DefaultModel;

factory DefaultModel.fromJson(Map<String, dynamic> json) => _$DefaultModelFromJson(json);
}
@freezed
class EtcModel with _$EtcModel{
const factory EtcModel({
  required String hobby,
  required String favoriteFood,
}) =_EtcModel;

factory EtcModel.fromJson(Map<String, dynamic> json) => _$EtcModelFromJson(json);
}
@freezed
class UserInfoModel with _$UserInfoModel{
const factory UserInfoModel({
  required DefaultModel defaultModel,
  required EtcModel etcModel
}) =_UserInfoModel;

factory UserInfoModel.fromJson(Map<String, dynamic> json) => _$UserInfoModelFromJson(json);
}

Question: I want to divide Json data in the same layer into two models. How can I do that?

I referred to the https://github.com/rrousselGit/freezed/issues/86 link, but it didn't work, and I'm not sure if this solves the problem I'm facing.

seokseok
  • 21
  • 2

1 Answers1

1

You can use readValue with the annotation @JsonKey to achieve this.

@freezed
class DefaultModel with _$DefaultModel {
  const factory DefaultModel({
    required String name,
    required int age,
    required Gender gender,
  }) = _DefaultModel;

  factory DefaultModel.fromJson(Map<String, dynamic> json) => _$DefaultModelFromJson(json);
}

enum Gender { M, F, O }

@freezed
class EtcModel with _$EtcModel {
  const factory EtcModel({
    required String hobby,
    required String favoriteFood,
  }) = _EtcModel;

  factory EtcModel.fromJson(Map<String, dynamic> json) => _$EtcModelFromJson(json);
}

@freezed
class UserInfoModel with _$UserInfoModel {
  const factory UserInfoModel({
    @JsonKey(readValue: convertJson) required DefaultModel defaultModel,
    @JsonKey(readValue: convertJson) required EtcModel etcModel,
  }) = _UserInfoModel;

  factory UserInfoModel.fromJson(Map<String, dynamic> json) => _$UserInfoModelFromJson(json);
}

Map<String, dynamic> convertJson(Map<dynamic, dynamic> json, String name) => json.map((key, value) => MapEntry(key.toString(), value));
Alex Sunder Singh
  • 2,378
  • 1
  • 7
  • 17