-
Notifications
You must be signed in to change notification settings - Fork 436
Open
Description
The following comes from the README file for json_serializable:
import 'package:json_annotation/json_annotation.dart';
part 't.g.dart';
@JsonSerializable()
class Sample1 {
Sample1(this.value);
factory Sample1.fromJson(Map<String, dynamic> json) => _$Sample1FromJson(json);
// Sample2 is NOT annotated with @JsonSerializable(), but that's okay
// The class has a `fromJson` constructor and a `toJson` method, which is
// all that is required.
final Sample2 value;
Map<String, dynamic> toJson() => _$Sample1ToJson(this);
}
class Sample2 {
Sample2(this.value);
// The convention is for `fromJson` to take a single parameter of type
// `Map<String, dynamic>` but any JSON-compatible type is allowed.
factory Sample2.fromJson(int value) => Sample2(value);
final int value;
// The convention is for `toJson` to take return a type of
// `Map<String, dynamic>` but any JSON-compatible type is allowed.
int toJson() => value;
}
If I run dart run build_runner build on this code, it generates the following:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 't.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Sample1 _$Sample1FromJson(Map<String, dynamic> json) =>
Sample1(Sample2.fromJson((json['value'] as num).toInt()));
Map<String, dynamic> _$Sample1ToJson(Sample1 instance) => <String, dynamic>{
'value': instance.value,
};
The generated code is wrong—it never calls .toJson on the Sample2 instance.
Metadata
Metadata
Assignees
Labels
No labels