google / google/json_serializable.dart

Generic argument factories does not work with toJson when using mixin

Open
#1,208 4 comments 4 reactions 0 assignees View on GitHub
P3 low State: help wanted Type: bug
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

The following file throws in the generator (probably because it tries to compare the type `Child` with `ChildMixin`).
I also reported this at https://github.com/rrousselGit/freezed/issues/766 but perhaps it's something that can be fixed in json_serializable.

If I move the `toJson` method to the Child class, it works fine.

build_runner build -v
```
[SEVERE] json_serializable on lib/src/bug.dart:

RangeError (index): Invalid value: Only valid value is 0: -1
dart:core List.[]
package:json_serializable/src/type_helpers/json_helper.dart 158:39 _helperParams
package:json_serializable/src/type_helpers/json_helper.dart 51:9 JsonHelper.serialize
package:json_serializable/src/type_helper_ctx.dart 56:31 TypeHelperCtx.serialize.
dart:core Iterable.firstWhere
package:json_serializable/src/type_helper_ctx.dart 88:46 TypeHelperCtx._run
package:json_serializable/src/type_helper_ctx.dart 53:64 TypeHelperCtx.serialize
package:json_serializable/src/encoder_helper.dart 153:12 EncodeHelper._serializeField
package:json_serializable/src/encoder_helper.dart 81:42 EncodeHelper._writeToJsonSimple.
dart:core StringBuffer.writeAll
package:json_serializable/src/encoder_helper.dart 78:9 EncodeHelper._writeToJsonSimple
package:json_serializable/src/encoder_helper.dart 66:7 EncodeHelper.createToJson
dart:_internal WhereIterator.moveNext
package:json_serializable/src/json_part_builder.dart 64:27 _UnifiedGenerator.generate
package:source_gen/src/builder.dart 352:23 _generate

```

pubspec.yaml
```yaml
environment:
sdk: '>=2.18.1 <3.0.0'

dev_dependencies:
build_runner: ^2.2.1
json_serializable: ^6.4.0
dependencies:
json_annotation: ^4.7.0
```

bug.dart
```dart
import 'package:json_annotation/json_annotation.dart';

part 'bug.g.dart';

@JsonSerializable()
class Person {
final Child firstName;

Person({required this.firstName});

factory Person.fromJson(Map json) => _$PersonFromJson(json);
Map toJson() => _$PersonToJson(this);
}

@JsonSerializable(genericArgumentFactories: true)
class Child with ChildMixin {
final T content;

Child({required this.content});

factory Child.fromJson(
Map json, T Function(Object? json) fromJsonT) =>
_$ChildFromJson(json, fromJsonT);
}

mixin ChildMixin {
Map toJson(Object Function(T) toJsonT) =>
_$ChildToJson(this, toJsonT);
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.