Freezed: toJson not generated for list of custom class

Created on 4 Aug 2020  ·  2Comments  ·  Source: rrousselGit/freezed

Hi.
I have the following Result class which wrap generic data

@freezed
abstract class Result<T> with _$Result<T> {
  const factory Result(
    @ResultDataConverter() T data, {
    @required bool local,
  }) = Data<T>;

  const factory Result.error([String message]) = Error<T>;

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

and with a TestData class from another file like this

@freezed
abstract class TestData with _$TestData {
  const factory TestData(
    String id,
    String simple,
    List<String> strList,
    List<CustomModel> customModels,
  ) = Data;

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

@freezed
abstract class CustomModel with _$CustomModel {
  const factory CustomModel(String id) = _CustomModel;

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

after build generation the TestData class does not generate valid toJson for List of CustomModel
generated code is (fromJson is correct!)

_$Data _$_$DataFromJson(Map<String, dynamic> json) {
  return _$Data(
    json['id'] as String,
    json['simple'] as String,
    (json['strList'] as List)?.map((e) => e as String)?.toList(),
    (json['customModels'] as List)
        ?.map((e) =>
            e == null ? null : CustomModel.fromJson(e as Map<String, dynamic>))
        ?.toList(),
  );
}

Map<String, dynamic> _$_$DataToJson(_$Data instance) => <String, dynamic>{
    'id': instance.id,
    'simple': instance.simple,
    'strList': instance.strList,
    'customModels': instance.customModels, //here is the problem, it should be -> instance.customModels.map((e) => e.toJson()).toList()
};

I don't know what is the problem, does I forget something? or should provide toJson through annotation?
Thanks for your help

Most helpful comment

You need to add @/JsonSerializable(explicitToJson: true) on the constructor of TestData

All 2 comments

You need to add @/JsonSerializable(explicitToJson: true) on the constructor of TestData

Thats worked. thanks for your quick response

Was this page helpful?
0 / 5 - 0 ratings