Skip to content

feature: default to creating toJson function instead of a mixin #254

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 16, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions json_serializable/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
## 0.6.0

* **BREAKING** By default, code generated to support `toJson` now creates
a top-level function instead of a mixin. The default for the
`generate_to_json_function` is now `true`. To opt-out of this change,
set `generate_to_json_function` to `false`.

* Now supports changing the serialized values of enums using `JsonValue`.

```dart
Expand Down
28 changes: 12 additions & 16 deletions json_serializable/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,13 @@ import 'package:json_annotation/json_annotation.dart';
part 'example.g.dart';

@JsonSerializable(nullable: false)
class Person extends Object with _$PersonSerializerMixin {
class Person {
final String firstName;
final String lastName;
final DateTime dateOfBirth;
Person({this.firstName, this.lastName, this.dateOfBirth});
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
```

Expand All @@ -48,16 +49,11 @@ Person _$PersonFromJson(Map<String, dynamic> json) {
dateOfBirth: DateTime.parse(json['dateOfBirth'] as String));
}

abstract class _$PersonSerializerMixin {
String get firstName;
String get lastName;
DateTime get dateOfBirth;
Map<String, dynamic> toJson() => <String, dynamic>{
'firstName': firstName,
'lastName': lastName,
'dateOfBirth': dateOfBirth.toIso8601String()
};
}
Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
'firstName': instance.firstName,
'lastName': instance.lastName,
'dateOfBirth': instance.dateOfBirth.toIso8601String()
};
```

# Build configuration
Expand Down Expand Up @@ -85,14 +81,14 @@ targets:
# Options configure how source code is generated for every
# `@JsonSerializable`-annotated class in the package.
#
# The default value for each of them: `false`.
# The default value for each is listed.
#
# For usage information, reference the corresponding field in
# `JsonSerializableGenerator`.
use_wrappers: true
any_map: true
checked: true
explicit_to_json: true
use_wrappers: false
any_map: false
checked: false
explicit_to_json: false
generate_to_json_function: true
```

Expand Down
4 changes: 2 additions & 2 deletions json_serializable/example/example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// ignore_for_file: annotate_overrides, hash_and_equals
import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart';

@JsonSerializable(nullable: false)
class Person extends Object with _$PersonSerializerMixin {
class Person {
final String firstName;
final String lastName;
final DateTime dateOfBirth;
Person({this.firstName, this.lastName, this.dateOfBirth});
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
15 changes: 5 additions & 10 deletions json_serializable/example/example.g.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,8 @@ Person _$PersonFromJson(Map<String, dynamic> json) {
dateOfBirth: DateTime.parse(json['dateOfBirth'] as String));
}

abstract class _$PersonSerializerMixin {
String get firstName;
String get lastName;
DateTime get dateOfBirth;
Map<String, dynamic> toJson() => <String, dynamic>{
'firstName': firstName,
'lastName': lastName,
'dateOfBirth': dateOfBirth.toIso8601String()
};
}
Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
'firstName': instance.firstName,
'lastName': instance.lastName,
'dateOfBirth': instance.dateOfBirth.toIso8601String()
};
2 changes: 1 addition & 1 deletion json_serializable/lib/src/json_part_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Builder jsonPartBuilder({
bool anyMap = false,
bool checked = false,
bool explicitToJson = false,
bool generateToJsonFunction = false,
bool generateToJsonFunction = true,
}) {
return new PartBuilder([
new JsonSerializableGenerator(
Expand Down
22 changes: 11 additions & 11 deletions json_serializable/lib/src/json_serializable_generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -95,26 +95,26 @@ class JsonSerializableGenerator
/// Controls how `toJson` functionality is generated for all types processed
/// by this generator.
///
/// If `false` (the default), a private `_$ClassNameSerializerMixin` class is
/// created in the generated part file which contains a `toJson` method.
///
/// Mix in this class to the source class:
/// If `true` (the default), then a top-level function is created that you can reference
/// from your class.
///
/// ```dart
/// @JsonSerializable()
/// class Example extends Object with _$ExampleSerializerMixin {
/// class Example {
/// // ...
/// Map<String, dynamic> toJson() => _$ExampleToJson(this);
/// }
/// ```
///
/// If `true`, then a top-level function is created that you can reference
/// from your class.
/// If `false`, a private `_$ClassNameSerializerMixin` class is
/// created in the generated part file which contains a `toJson` method.
///
/// Mix in this class to the source class:
///
/// ```dart
/// @JsonSerializable()
/// class Example {
/// class Example extends Object with _$ExampleSerializerMixin {
/// // ...
/// Map<String, dynamic> toJson() => _$ExampleToJson(this);
/// }
/// ```
final bool generateToJsonFunction;
Expand All @@ -129,12 +129,12 @@ class JsonSerializableGenerator
bool anyMap = false,
bool checked = false,
bool explicitToJson = false,
bool generateToJsonFunction = false,
bool generateToJsonFunction = true,
}) : this.useWrappers = useWrappers ?? false,
this.anyMap = anyMap ?? false,
this.checked = checked ?? false,
this.explicitToJson = explicitToJson ?? false,
this.generateToJsonFunction = generateToJsonFunction ?? false,
this.generateToJsonFunction = generateToJsonFunction ?? true,
this._typeHelpers = typeHelpers ?? _defaultHelpers;

/// Creates an instance of [JsonSerializableGenerator].
Expand Down
4 changes: 2 additions & 2 deletions json_serializable/lib/src/type_helpers/enum_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ String _enumValueMapFromType(DartType targetType) {
return null;
}

var items = enumMap.entries.map((e) =>
' ${targetType.name}.${e.key.name}: ${jsonLiteralAsDart(e.value, false)}');
var items = enumMap.entries.map((e) => ' ${targetType.name}.${e.key.name}: '
'${jsonLiteralAsDart(e.value, false)}');

return 'const ${_constMapName(targetType)} = '
'const <${targetType.name}, dynamic>{\n${items.join(',\n')}\n};';
Expand Down
2 changes: 1 addition & 1 deletion json_serializable/test/config_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ const _validConfig = const {
'any_map': true,
'checked': true,
'explicit_to_json': true,
'generate_to_json_function': true,
'generate_to_json_function': false,
};

const _invalidConfig = const {
Expand Down
22 changes: 17 additions & 5 deletions json_serializable/test/integration/json_test_example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// ignore_for_file: annotate_overrides, hash_and_equals
// ignore_for_file: hash_and_equals
import 'dart:collection';

import 'package:json_annotation/json_annotation.dart';
Expand All @@ -11,7 +11,7 @@ import 'json_test_common.dart';
part 'json_test_example.g.dart';

@JsonSerializable()
class Person extends Object with _$PersonSerializerMixin {
class Person {
final String firstName, middleName, lastName;
final DateTime dateOfBirth;
@JsonKey(name: '\$house')
Expand All @@ -26,6 +26,9 @@ class Person extends Object with _$PersonSerializerMixin {

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

Map<String, dynamic> toJson() => _$PersonToJson(this);

@override
bool operator ==(Object other) =>
other is Person &&
firstName == other.firstName &&
Expand All @@ -37,7 +40,7 @@ class Person extends Object with _$PersonSerializerMixin {
}

@JsonSerializable()
class Order extends Object with _$OrderSerializerMixin {
class Order {
/// Used to test that `disallowNullValues: true` forces `includeIfNull: false`
@JsonKey(disallowNullValue: true)
int count;
Expand Down Expand Up @@ -74,6 +77,9 @@ class Order extends Object with _$OrderSerializerMixin {

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

Map<String, dynamic> toJson() => _$OrderToJson(this);

@override
bool operator ==(Object other) =>
other is Order &&
count == other.count &&
Expand All @@ -83,7 +89,7 @@ class Order extends Object with _$OrderSerializerMixin {
}

@JsonSerializable()
class Item extends ItemCore with _$ItemSerializerMixin {
class Item extends ItemCore {
@JsonKey(includeIfNull: false, name: 'item-number')
int itemNumber;
List<DateTime> saleDates;
Expand All @@ -93,6 +99,9 @@ class Item extends ItemCore with _$ItemSerializerMixin {

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

Map<String, dynamic> toJson() => _$ItemToJson(this);

@override
bool operator ==(Object other) =>
other is Item &&
price == other.price &&
Expand All @@ -101,7 +110,7 @@ class Item extends ItemCore with _$ItemSerializerMixin {
}

@JsonSerializable()
class Numbers extends Object with _$NumbersSerializerMixin {
class Numbers {
List<int> ints;
List<num> nums;
List<double> doubles;
Expand All @@ -120,6 +129,9 @@ class Numbers extends Object with _$NumbersSerializerMixin {
factory Numbers.fromJson(Map<String, dynamic> json) =>
_$NumbersFromJson(json);

Map<String, dynamic> toJson() => _$NumbersToJson(this);

@override
bool operator ==(Object other) =>
other is Numbers &&
deepEquals(ints, other.ints) &&
Expand Down
Loading