Skip to content

Commit 8345818

Browse files
committed
WIP: default to using toJson function
1 parent 749573e commit 8345818

20 files changed

+333
-464
lines changed

json_serializable/README.md

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,13 @@ import 'package:json_annotation/json_annotation.dart';
2727
part 'example.g.dart';
2828
2929
@JsonSerializable(nullable: false)
30-
class Person extends Object with _$PersonSerializerMixin {
30+
class Person {
3131
final String firstName;
3232
final String lastName;
3333
final DateTime dateOfBirth;
3434
Person({this.firstName, this.lastName, this.dateOfBirth});
3535
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
36+
Map<String, dynamic> toJson() => _$PersonToJson(this);
3637
}
3738
```
3839

@@ -48,16 +49,11 @@ Person _$PersonFromJson(Map<String, dynamic> json) {
4849
dateOfBirth: DateTime.parse(json['dateOfBirth'] as String));
4950
}
5051
51-
abstract class _$PersonSerializerMixin {
52-
String get firstName;
53-
String get lastName;
54-
DateTime get dateOfBirth;
55-
Map<String, dynamic> toJson() => <String, dynamic>{
56-
'firstName': firstName,
57-
'lastName': lastName,
58-
'dateOfBirth': dateOfBirth.toIso8601String()
59-
};
60-
}
52+
Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
53+
'firstName': instance.firstName,
54+
'lastName': instance.lastName,
55+
'dateOfBirth': instance.dateOfBirth.toIso8601String()
56+
};
6157
```
6258

6359
# Build configuration
@@ -93,7 +89,7 @@ targets:
9389
any_map: true
9490
checked: true
9591
explicit_to_json: true
96-
generate_to_json_function: true
92+
generate_to_json_mixin: true
9793
```
9894
9995
[example]: https://github.com/dart-lang/json_serializable/blob/master/example

json_serializable/example/example.dart

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@ import 'package:json_annotation/json_annotation.dart';
88
part 'example.g.dart';
99

1010
@JsonSerializable(nullable: false)
11-
class Person extends Object with _$PersonSerializerMixin {
11+
class Person {
1212
final String firstName;
1313
final String lastName;
1414
final DateTime dateOfBirth;
1515
Person({this.firstName, this.lastName, this.dateOfBirth});
1616
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
17+
Map<String, dynamic> toJson() => _$PersonToJson(this);
1718
}

json_serializable/example/example.g.dart

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,8 @@ Person _$PersonFromJson(Map<String, dynamic> json) {
1717
dateOfBirth: DateTime.parse(json['dateOfBirth'] as String));
1818
}
1919

20-
abstract class _$PersonSerializerMixin {
21-
String get firstName;
22-
String get lastName;
23-
DateTime get dateOfBirth;
24-
Map<String, dynamic> toJson() => <String, dynamic>{
25-
'firstName': firstName,
26-
'lastName': lastName,
27-
'dateOfBirth': dateOfBirth.toIso8601String()
28-
};
29-
}
20+
Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
21+
'firstName': instance.firstName,
22+
'lastName': instance.lastName,
23+
'dateOfBirth': instance.dateOfBirth.toIso8601String()
24+
};

json_serializable/lib/builder.dart

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ Builder jsonSerializable(BuilderOptions options) {
3131
checked: optionsMap.remove('checked') as bool,
3232
anyMap: optionsMap.remove('any_map') as bool,
3333
explicitToJson: optionsMap.remove('explicit_to_json') as bool,
34-
generateToJsonFunction:
35-
optionsMap.remove('generate_to_json_function') as bool,
34+
generateToJsonMixin: optionsMap.remove('generate_to_json_mixin') as bool,
3635
);
3736

3837
if (optionsMap.isNotEmpty) {

json_serializable/lib/src/encoder_helper.dart

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import 'type_helper.dart';
1212
abstract class EncodeHelper implements HelperCore {
1313
String _fieldAccess(FieldElement field) {
1414
var fieldAccess = field.name;
15-
if (generator.generateToJsonFunction) {
15+
if (!generator.generateToJsonMixin) {
1616
fieldAccess = '$_toJsonParamName.$fieldAccess';
1717
}
1818
return fieldAccess;
@@ -29,11 +29,7 @@ abstract class EncodeHelper implements HelperCore {
2929

3030
var buffer = new StringBuffer();
3131

32-
if (generator.generateToJsonFunction) {
33-
var functionName = '${prefix}ToJson${genericClassArgumentsImpl(true)}';
34-
buffer.write('Map<String, dynamic> $functionName'
35-
'($targetClassReference $_toJsonParamName) ');
36-
} else {
32+
if (generator.generateToJsonMixin) {
3733
//
3834
// Generate the mixin class
3935
//
@@ -47,12 +43,16 @@ abstract class EncodeHelper implements HelperCore {
4743
}
4844

4945
buffer.write(' Map<String, dynamic> toJson() ');
46+
} else {
47+
var functionName = '${prefix}ToJson${genericClassArgumentsImpl(true)}';
48+
buffer.write('Map<String, dynamic> $functionName'
49+
'($targetClassReference $_toJsonParamName) ');
5050
}
5151

5252
var writeNaive = accessibleFields.every(_writeJsonValueNaive);
5353

5454
if (generator.useWrappers) {
55-
var param = generator.generateToJsonFunction ? _toJsonParamName : 'this';
55+
var param = generator.generateToJsonMixin ? 'this' : _toJsonParamName;
5656
buffer.writeln('=> new ${_wrapperClassName(false)}($param);');
5757
} else {
5858
if (writeNaive) {
@@ -64,7 +64,7 @@ abstract class EncodeHelper implements HelperCore {
6464
}
6565
}
6666

67-
if (!generator.generateToJsonFunction) {
67+
if (generator.generateToJsonMixin) {
6868
// end of the mixin class
6969
buffer.writeln('}');
7070
}
@@ -81,9 +81,9 @@ abstract class EncodeHelper implements HelperCore {
8181
buffer.writeln();
8282
// TODO(kevmoo): write JsonMapWrapper if annotation lib is prefix-imported
8383

84-
var fieldType = generator.generateToJsonFunction
85-
? targetClassReference
86-
: _mixinClassName(false);
84+
var fieldType = generator.generateToJsonMixin
85+
? _mixinClassName(false)
86+
: targetClassReference;
8787

8888
buffer.writeln('''
8989
class ${_wrapperClassName(true)} extends \$JsonMapWrapper {
@@ -160,7 +160,7 @@ class ${_wrapperClassName(true)} extends \$JsonMapWrapper {
160160
}
161161

162162
/// Name of the parameter used when generating top-level `toJson` functions
163-
/// if [JsonSerializableGenerator.generateToJsonFunction] is `true`.
163+
/// if [JsonSerializableGenerator.generateToJsonMixin] is `false`.
164164
static const _toJsonParamName = 'instance';
165165

166166
void _writeToJsonWithNullChecks(
@@ -183,7 +183,7 @@ class ${_wrapperClassName(true)} extends \$JsonMapWrapper {
183183
// access with `this.`.
184184
if (safeFieldAccess == generatedLocalVarName ||
185185
safeFieldAccess == toJsonMapHelperName) {
186-
assert(!generator.generateToJsonFunction,
186+
assert(generator.generateToJsonMixin,
187187
'This code path should only be hit during the mixin codepath.');
188188
safeFieldAccess = 'this.$safeFieldAccess';
189189
}

json_serializable/lib/src/json_part_builder.dart

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,15 @@ Builder jsonPartBuilder({
2727
bool anyMap = false,
2828
bool checked = false,
2929
bool explicitToJson = false,
30-
bool generateToJsonFunction = false,
30+
bool generateToJsonMixin = false,
3131
}) {
3232
return new PartBuilder([
3333
new JsonSerializableGenerator(
3434
useWrappers: useWrappers,
3535
anyMap: anyMap,
3636
checked: checked,
3737
explicitToJson: explicitToJson,
38-
generateToJsonFunction: generateToJsonFunction,
38+
generateToJsonMixin: generateToJsonMixin,
3939
),
4040
const JsonLiteralGenerator()
4141
], header: header, formatOutput: formatOutput);

json_serializable/lib/src/json_serializable_generator.dart

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -95,29 +95,29 @@ class JsonSerializableGenerator
9595
/// Controls how `toJson` functionality is generated for all types processed
9696
/// by this generator.
9797
///
98-
/// If `false` (the default), a private `_$ClassNameSerializerMixin` class is
99-
/// created in the generated part file which contains a `toJson` method.
100-
///
101-
/// Mix in this class to the source class:
98+
/// If `false` (the default), then a top-level function is created that you
99+
/// can reference from your class.
102100
///
103101
/// ```dart
104102
/// @JsonSerializable()
105-
/// class Example extends Object with _$ExampleSerializerMixin {
103+
/// class Example {
106104
/// // ...
105+
/// Map<String, dynamic> toJson() => _$ExampleToJson(this);
107106
/// }
108107
/// ```
109108
///
110-
/// If `true`, then a top-level function is created that you can reference
111-
/// from your class.
109+
/// If `true`, a private `_$ClassNameSerializerMixin` class is created in the
110+
/// generated part file which contains a `toJson` method.
111+
///
112+
/// Mix in this class to the source class:
112113
///
113114
/// ```dart
114115
/// @JsonSerializable()
115-
/// class Example {
116+
/// class Example extends Object with _$ExampleSerializerMixin {
116117
/// // ...
117-
/// Map<String, dynamic> toJson() => _$ExampleToJson(this);
118118
/// }
119119
/// ```
120-
final bool generateToJsonFunction;
120+
final bool generateToJsonMixin;
121121

122122
/// Creates an instance of [JsonSerializableGenerator].
123123
///
@@ -129,12 +129,12 @@ class JsonSerializableGenerator
129129
bool anyMap = false,
130130
bool checked = false,
131131
bool explicitToJson = false,
132-
bool generateToJsonFunction = false,
132+
bool generateToJsonMixin = false,
133133
}) : this.useWrappers = useWrappers ?? false,
134134
this.anyMap = anyMap ?? false,
135135
this.checked = checked ?? false,
136136
this.explicitToJson = explicitToJson ?? false,
137-
this.generateToJsonFunction = generateToJsonFunction ?? false,
137+
this.generateToJsonMixin = generateToJsonMixin ?? false,
138138
this._typeHelpers = typeHelpers ?? _defaultHelpers;
139139

140140
/// Creates an instance of [JsonSerializableGenerator].
@@ -147,13 +147,13 @@ class JsonSerializableGenerator
147147
bool useWrappers = false,
148148
bool anyMap = false,
149149
bool checked = false,
150-
bool generateToJsonFunction = false,
150+
bool generateToJsonMixin = false,
151151
}) =>
152152
new JsonSerializableGenerator(
153153
useWrappers: useWrappers,
154154
anyMap: anyMap,
155155
checked: checked,
156-
generateToJsonFunction: generateToJsonFunction,
156+
generateToJsonMixin: generateToJsonMixin,
157157
typeHelpers:
158158
new List.unmodifiable(typeHelpers.followedBy(_defaultHelpers)));
159159

json_serializable/test/config_test.dart

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ const _validConfig = const {
102102
'any_map': true,
103103
'checked': true,
104104
'explicit_to_json': true,
105-
'generate_to_json_function': true,
105+
'generate_to_json_mixin': true,
106106
};
107107

108108
const _invalidConfig = const {
@@ -111,5 +111,5 @@ const _invalidConfig = const {
111111
'any_map': 42,
112112
'checked': 42,
113113
'explicit_to_json': 42,
114-
'generate_to_json_function': 42,
114+
'generate_to_json_mixin': 42,
115115
};

json_serializable/test/integration/json_test_example.dart

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import 'json_test_common.dart';
1111
part 'json_test_example.g.dart';
1212

1313
@JsonSerializable()
14-
class Person extends Object with _$PersonSerializerMixin {
14+
class Person {
1515
final String firstName, middleName, lastName;
1616
final DateTime dateOfBirth;
1717
@JsonKey(name: '\$house')
@@ -26,6 +26,8 @@ class Person extends Object with _$PersonSerializerMixin {
2626

2727
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
2828

29+
Map<String, dynamic> toJson() => _$PersonToJson(this);
30+
2931
bool operator ==(Object other) =>
3032
other is Person &&
3133
firstName == other.firstName &&
@@ -37,7 +39,7 @@ class Person extends Object with _$PersonSerializerMixin {
3739
}
3840

3941
@JsonSerializable()
40-
class Order extends Object with _$OrderSerializerMixin {
42+
class Order {
4143
/// Used to test that `disallowNullValues: true` forces `includeIfNull: false`
4244
@JsonKey(disallowNullValue: true)
4345
int count;
@@ -74,6 +76,8 @@ class Order extends Object with _$OrderSerializerMixin {
7476

7577
factory Order.fromJson(Map<String, dynamic> json) => _$OrderFromJson(json);
7678

79+
Map<String, dynamic> toJson() => _$OrderToJson(this);
80+
7781
bool operator ==(Object other) =>
7882
other is Order &&
7983
count == other.count &&
@@ -83,7 +87,7 @@ class Order extends Object with _$OrderSerializerMixin {
8387
}
8488

8589
@JsonSerializable()
86-
class Item extends ItemCore with _$ItemSerializerMixin {
90+
class Item extends ItemCore {
8791
@JsonKey(includeIfNull: false, name: 'item-number')
8892
int itemNumber;
8993
List<DateTime> saleDates;
@@ -93,6 +97,8 @@ class Item extends ItemCore with _$ItemSerializerMixin {
9397

9498
factory Item.fromJson(Map<String, dynamic> json) => _$ItemFromJson(json);
9599

100+
Map<String, dynamic> toJson() => _$ItemToJson(this);
101+
96102
bool operator ==(Object other) =>
97103
other is Item &&
98104
price == other.price &&
@@ -101,7 +107,7 @@ class Item extends ItemCore with _$ItemSerializerMixin {
101107
}
102108

103109
@JsonSerializable()
104-
class Numbers extends Object with _$NumbersSerializerMixin {
110+
class Numbers {
105111
List<int> ints;
106112
List<num> nums;
107113
List<double> doubles;
@@ -120,6 +126,8 @@ class Numbers extends Object with _$NumbersSerializerMixin {
120126
factory Numbers.fromJson(Map<String, dynamic> json) =>
121127
_$NumbersFromJson(json);
122128

129+
Map<String, dynamic> toJson() => _$NumbersToJson(this);
130+
123131
bool operator ==(Object other) =>
124132
other is Numbers &&
125133
deepEquals(ints, other.ints) &&

0 commit comments

Comments
 (0)