google / google/json_serializable.dart

Invalid code generated for `checked: true` when `json_annotation` is imported with a prefix

Open
#1,199 2 comments 0 reactions 0 assignees View on GitHub
P2 medium pkg:json_serializable State: help wanted Type: enhancement
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

I encountered some incorrect code generation when setting `checked: true` and importing `json_annotation` with a prefix:
```
import 'package:json_annotation/json_annotation.dart' as _i1;

part 'my_class.g.dart';

@_i1.JsonSerializable(checked: true)
class MyClass {
final String field1;
final String field2;

MyClass({
required this.field1,
required this.field2,
});

factory MyClass.fromJson(Map json) =>
_$MyClassFromJson(json);
}
```

The generated code attempts to use the unqualified `$checkedCreate` instead of `_i1.$checkedCreate`:
```
// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'my_class.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

MyClass _$MyClassFromJson(Map json) => $checkedCreate(
'MyClass',
json,
($checkedConvert) {
final val = MyClass(
field1: $checkedConvert('field1', (v) => v as String),
field2: $checkedConvert('field2', (v) => v as String),
);
return val;
},
);

Map _$MyClassToJson(MyClass instance) => {
'field1': instance.field1,
'field2': instance.field2,
};
```

This results in an error in the generated code:
```
The function '$checkedCreate' isn't defined.
```

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.