Skip to content

Support inherited fields #107

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 2 commits into from
Feb 23, 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
7 changes: 6 additions & 1 deletion json_serializable/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
## 0.3.3
## 0.4.0

* **Potentially Breaking** Inherited fields are now processed and used
when generating serialization and deserialization code. There is a possibility
that the generated code may change in undesired ways for classes annotated for
`v0.3`.

* Avoid unnecessary braces in string escapes.

Expand Down
70 changes: 59 additions & 11 deletions json_serializable/lib/src/json_serializable_generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import 'dart:collection';

import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
// ignore: implementation_imports
import 'package:analyzer/src/dart/resolver/inheritance_manager.dart'
show InheritanceManager;
import 'package:analyzer/analyzer.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:source_gen/source_gen.dart';
Expand Down Expand Up @@ -75,11 +78,10 @@ class JsonSerializableGenerator
}

var classElement = element as ClassElement;
var className = classElement.name;

// Get all of the fields that need to be assigned
// TODO: support overriding the field set with an annotation option
var fieldsList = classElement.fields.where((e) => !e.isStatic).toList();
var fieldsList = _listFields(classElement);

var undefinedFields =
fieldsList.where((fe) => fe.type.isUndefined).toList();
Expand All @@ -94,7 +96,7 @@ class JsonSerializableGenerator

// Sort these in the order in which they appear in the class
// Sadly, `classElement.fields` puts properties after fields
fieldsList.sort((a, b) => _offsetFor(a).compareTo(_offsetFor(b)));
fieldsList.sort(_sortByLocation);

// Explicitly using `LinkedHashMap` – we want these ordered.
var fields = new LinkedHashMap<String, FieldElement>.fromIterable(
Expand All @@ -103,7 +105,7 @@ class JsonSerializableGenerator

// Get the constructor to use for the factory

var prefix = '_\$$className';
var prefix = '_\$${classElement.name}';

var buffer = new StringBuffer();

Expand Down Expand Up @@ -535,14 +537,37 @@ final _jsonKeyExpando = new Expando<JsonKey>();

final _jsonKeyChecker = new TypeChecker.fromRuntime(JsonKey);

/// Returns the offset of given field/property in its source file – with a
/// preference for the getter if it's defined.
int _offsetFor(FieldElement e) {
if (e.getter != null && e.getter.nameOffset != e.nameOffset) {
assert(e.nameOffset == -1);
return e.getter.nameOffset;
final _dartCoreObjectChecker = new TypeChecker.fromRuntime(Object);

int _sortByLocation(FieldElement a, FieldElement b) {
var checkerA = new TypeChecker.fromStatic(a.enclosingElement.type);

if (!checkerA.isExactly(b.enclosingElement)) {
// in this case, you want to prioritize the enclosingElement that is more
// "super".

if (checkerA.isSuperOf(b.enclosingElement)) {
return -1;
}

var checkerB = new TypeChecker.fromStatic(b.enclosingElement.type);

if (checkerB.isSuperOf(a.enclosingElement)) {
return 1;
}
}

/// Returns the offset of given field/property in its source file – with a
/// preference for the getter if it's defined.
int _offsetFor(FieldElement e) {
if (e.getter != null && e.getter.nameOffset != e.nameOffset) {
assert(e.nameOffset == -1);
return e.getter.nameOffset;
}
return e.nameOffset;
}
return e.nameOffset;

return _offsetFor(a).compareTo(_offsetFor(b));
}

final _notSupportedWithTypeHelpersMsg =
Expand All @@ -558,3 +583,26 @@ InvalidGenerationSourceError _createInvalidGenerationError(
return new InvalidGenerationSourceError(message,
todo: 'Make sure all of the types are serializable.');
}

/// Returns a list of all instance, [FieldElement] items for [element] and
/// super classes.
List<FieldElement> _listFields(ClassElement element) {
// Get all of the fields that need to be assigned
// TODO: support overriding the field set with an annotation option
var fieldsList = element.fields.where((e) => !e.isStatic).toList();

var manager = new InheritanceManager(element.library);

for (var v in manager.getMembersInheritedFromClasses(element).values) {
assert(v is! FieldElement);
if (_dartCoreObjectChecker.isExactly(v.enclosingElement)) {
continue;
}

if (v is PropertyAccessorElement && v.variable is FieldElement) {
fieldsList.add(v.variable as FieldElement);
}
}

return fieldsList;
}
2 changes: 1 addition & 1 deletion json_serializable/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: json_serializable
version: 0.3.3-dev
version: 0.4.0-dev
author: Dart Team <misc@dartlang.org>
description: Generates utilities to aid in serializing to/from JSON.
homepage: https://github.com/dart-lang/json_serializable
Expand Down
86 changes: 86 additions & 0 deletions json_serializable/test/json_serializable_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,92 @@ abstract class _$OrderSerializerMixin {
(e) => e.message,
'The class `NoCtorClass` has no default constructor.')));
});

test('super types', () async {
var output = await runForElementNamed('SubType');

String expected;
if (generator.useWrappers) {
expected =
r'''SubType _$SubTypeFromJson(Map<String, dynamic> json) => new SubType(
json['subTypeViaCtor'] as int, json['super-type-via-ctor'] as int)
..superTypeReadWrite = json['superTypeReadWrite'] as int
..subTypeReadWrite = json['subTypeReadWrite'] as int;

abstract class _$SubTypeSerializerMixin {
int get superTypeViaCtor;
int get superTypeReadWrite;
int get subTypeViaCtor;
int get subTypeReadWrite;
Map<String, dynamic> toJson() => new _$SubTypeJsonMapWrapper(this);
}

class _$SubTypeJsonMapWrapper extends $JsonMapWrapper {
final _$SubTypeSerializerMixin _v;
_$SubTypeJsonMapWrapper(this._v);

@override
Iterable<String> get keys sync* {
yield 'super-type-via-ctor';
if (_v.superTypeReadWrite != null) {
yield 'superTypeReadWrite';
}
yield 'subTypeViaCtor';
yield 'subTypeReadWrite';
}

@override
dynamic operator [](Object key) {
if (key is String) {
switch (key) {
case 'super-type-via-ctor':
return _v.superTypeViaCtor;
case 'superTypeReadWrite':
return _v.superTypeReadWrite;
case 'subTypeViaCtor':
return _v.subTypeViaCtor;
case 'subTypeReadWrite':
return _v.subTypeReadWrite;
}
}
return null;
}
}
''';
} else {
expected =
r'''SubType _$SubTypeFromJson(Map<String, dynamic> json) => new SubType(
json['subTypeViaCtor'] as int, json['super-type-via-ctor'] as int)
..superTypeReadWrite = json['superTypeReadWrite'] as int
..subTypeReadWrite = json['subTypeReadWrite'] as int;

abstract class _$SubTypeSerializerMixin {
int get superTypeViaCtor;
int get superTypeReadWrite;
int get subTypeViaCtor;
int get subTypeReadWrite;
Map<String, dynamic> toJson() {
var val = <String, dynamic>{
'super-type-via-ctor': superTypeViaCtor,
};

void writeNotNull(String key, dynamic value) {
if (value != null) {
val[key] = value;
}
}

writeNotNull('superTypeReadWrite', superTypeReadWrite);
val['subTypeViaCtor'] = subTypeViaCtor;
val['subTypeReadWrite'] = subTypeReadWrite;
return val;
}
}
''';
}

expect(output, expected);
});
}

final _formatter = new dart_style.DartFormatter();
Expand Down
27 changes: 27 additions & 0 deletions json_serializable/test/src/json_serializable_test_input.dart
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,30 @@ class DupeKeys {
@JsonKey(name: 'a')
String str;
}

@JsonSerializable()
class SubType extends SuperType {
final int subTypeViaCtor;
int subTypeReadWrite;

SubType(this.subTypeViaCtor, int superTypeViaCtor) : super(superTypeViaCtor);
}

// NOTE: `SuperType` is intentionally after `SubType` in the source file to
// validate field ordering semantics.
class SuperType {
@JsonKey(name: 'super-type-via-ctor', nullable: false)
final int superTypeViaCtor;

@JsonKey(includeIfNull: false)
int superTypeReadWrite;

SuperType(this.superTypeViaCtor);

/// Add a property to try to throw-off the generator
int get priceHalf => priceFraction(2);

/// Add a method to try to throw-off the generator
int priceFraction(int other) =>
superTypeViaCtor == null ? null : superTypeViaCtor ~/ other;
}
11 changes: 8 additions & 3 deletions json_serializable/test/test_files/json_test_example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,13 @@ class Order extends Object with _$OrderSerializerMixin {
}

@JsonSerializable()
class Item extends Object with _$ItemSerializerMixin {
final int price;
class Item extends ItemCore with _$ItemSerializerMixin {
@JsonKey(includeIfNull: false, name: 'item-number')
int itemNumber;
List<DateTime> saleDates;
List<int> rates;

Item([this.price]);
Item([int price]) : super(price);

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

Expand All @@ -84,6 +83,12 @@ class Item extends Object with _$ItemSerializerMixin {
_deepEquals(saleDates, other.saleDates);
}

abstract class ItemCore {
final int price;

ItemCore(this.price);
}

bool _deepEquals(a, b) => const DeepCollectionEquality().equals(a, b);

class Platform {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,13 @@ class Order extends Object with _$OrderSerializerMixin {
}

@JsonSerializable(nullable: false)
class Item extends Object with _$ItemSerializerMixin {
final int price;
class Item extends ItemCore with _$ItemSerializerMixin {
@JsonKey(includeIfNull: false, name: 'item-number')
int itemNumber;
List<DateTime> saleDates;
List<int> rates;

Item([this.price]);
Item([int price]) : super(price);

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

Expand All @@ -90,6 +89,12 @@ class Item extends Object with _$ItemSerializerMixin {
_deepEquals(saleDates, other.saleDates);
}

abstract class ItemCore {
final int price;

ItemCore(this.price);
}

bool _deepEquals(a, b) => const DeepCollectionEquality().equals(a, b);

class Platform {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,13 @@ class Order extends Object with _$OrderSerializerMixin {
}

@JsonSerializable(nullable: false)
class Item extends Object with _$ItemSerializerMixin {
final int price;
class Item extends ItemCore with _$ItemSerializerMixin {
@JsonKey(includeIfNull: false, name: 'item-number')
int itemNumber;
List<DateTime> saleDates;
List<int> rates;

Item([this.price]);
Item([int price]) : super(price);

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

Expand All @@ -96,6 +95,12 @@ class Item extends Object with _$ItemSerializerMixin {
_deepEquals(saleDates, other.saleDates);
}

abstract class ItemCore {
final int price;

ItemCore(this.price);
}

bool _deepEquals(a, b) => const DeepCollectionEquality().equals(a, b);

class Platform {
Expand Down
11 changes: 8 additions & 3 deletions json_serializable/test/test_files/json_test_example.wrapped.dart
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,13 @@ class Order extends Object with _$OrderSerializerMixin {
}

@JsonSerializable()
class Item extends Object with _$ItemSerializerMixin {
final int price;
class Item extends ItemCore with _$ItemSerializerMixin {
@JsonKey(includeIfNull: false, name: 'item-number')
int itemNumber;
List<DateTime> saleDates;
List<int> rates;

Item([this.price]);
Item([int price]) : super(price);

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

Expand All @@ -90,6 +89,12 @@ class Item extends Object with _$ItemSerializerMixin {
_deepEquals(saleDates, other.saleDates);
}

abstract class ItemCore {
final int price;

ItemCore(this.price);
}

bool _deepEquals(a, b) => const DeepCollectionEquality().equals(a, b);

class Platform {
Expand Down