Freezed: 12.6 does not generate json_serializable code with nested object

Created on 21 Dec 2020  路  4Comments  路  Source: rrousselGit/freezed

`import 'package:freezed_annotation/freezed_annotation.dart';

part 'event_dto.freezed.dart';
part 'event_dto.g.dart';

@freezed
abstract class EventDto with _$EventDto {
factory EventDto({
@JsonKey(ignore: false) String id,
@required List dogs,
}) = _EventDto;

factory EventDto.fromJson(Map json) =>
_$EventDtoFromJson(json);
}`

`import 'package:freezed_annotation/freezed_annotation.dart';

part 'dog_dto.freezed.dart';
part 'dog_dto.g.dart';

@freezed
abstract class DogDto with _$DogDto {
factory DogDto({
@JsonKey(ignore: false) String id,
String name,
ImageDocFieldsDto images,
}) = _DogDto;`

json_serializable:json_serializable on lib/app/app_models/event/event_dto/event_dto.dart:

Could not generate toJson code for dogs because of type DogDto.
package:doggapp/app/app_models/event/event_dto/event_dto.freezed.dart:239:22
final List dogs;

g.dart will work with all the classes that don't have nested object.
All of the issues will be solved if I revert back to 0.11.6

bug

Most helpful comment

After freaking 90 minutes I found out I was using extends instead of with... My problem solved. Enjoy your holiday :)

All 4 comments

I am having the same problem on 12.6, because I am working on Beta I don't think I can downgrade to 0.11.6.

import 'package:freezed_annotation/freezed_annotation.dart';

part 'question.freezed.dart';
part 'question.g.dart';

@freezed
abstract class Question extends _$Question {
  const factory Question(
    @JsonKey(name: 'Id') String id,
    @JsonKey(name: 'Question') String question,
    @JsonKey(name: 'Answers') List<Answer> answers,
  ) = _Question;

  factory Question.fromJson(Map<String, dynamic> json) =>
      _$QuestionFromJson(json);
}
@freezed
abstract class Answer extends _$Answer {
  const factory Answer(
      @JsonKey(name: 'Id') String id,
      @JsonKey(name: 'Answer') String answer,
      @JsonKey(name: 'Rate') int rate,
      ) = _Answer;

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

Error:

[SEVERE] json_serializable:json_serializable on lib/model/question.dart:

Could not generate `toJson` code for `answers` because of type `Answer`.
package:evaluation/model/question.freezed.dart:143:22
final List<Answer> answers;
                   ^^^^^^^

Separating into different files doesn't change anything.

These are two separate issues.

For @linhdogg : your second class needs a "fromJson".
If it used to work before, that was a bug. The current behavior is expected

@MarcinusX I don't immediately why that wouldn't work. I'm not working for now. I will in a week or two

After freaking 90 minutes I found out I was using extends instead of with... My problem solved. Enjoy your holiday :)

Closing since the problems were answered

Was this page helpful?
0 / 5 - 0 ratings