Skip to content

allow optional parameters for types using fromJson() #72

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 1 commit into from
Nov 27, 2017
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
Empty file.
2 changes: 1 addition & 1 deletion json_serializable/lib/src/type_helpers/json_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class JsonHelper extends TypeHelper {
var fromJsonCtor =
classElement.constructors.firstWhere((ce) => ce.name == 'fromJson');
// TODO: should verify that this type is a valid JSON type...but for now...
var asCastType = fromJsonCtor.parameters.single.type;
var asCastType = fromJsonCtor.parameters.first.type;

var asCast = '';
if (!asCastType.isDynamic && !asCastType.isObject) {
Expand Down
18 changes: 18 additions & 0 deletions json_serializable/test/json_serializable_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,13 @@ abstract class _$OrderSerializerMixin {
});
}


test('class with fromJson() constructor with optional parameters', () async {
var output = await runForElementNamed('FromJsonOptionalParameters');

expect(output, contains('new ChildWithFromJson.fromJson'));
});

test('class with child json-able object', () async {
var output = await runForElementNamed('ParentObject');

Expand Down Expand Up @@ -321,6 +328,17 @@ class FinalFields {
FinalFields(this.a);
}

@JsonSerializable()
class FromJsonOptionalParameters {
final ChildWithFromJson child;

FromJsonOptionalParameters(this.child);
}

class ChildWithFromJson {
ChildWithFromJson.fromJson(json, {initValue: false}) {}
}

@JsonSerializable()
class ParentObject {
int number;
Expand Down