Skip to content

Commit 17ef8fa

Browse files
johnpryankevmoo
authored andcommitted
allow optional parameters for types using fromJson() (#72)
1 parent ebf37f3 commit 17ef8fa

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

json_serializable/json_serializable.iml

Whitespace-only changes.

json_serializable/lib/src/type_helpers/json_helper.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ class JsonHelper extends TypeHelper {
3333
var fromJsonCtor =
3434
classElement.constructors.firstWhere((ce) => ce.name == 'fromJson');
3535
// TODO: should verify that this type is a valid JSON type...but for now...
36-
var asCastType = fromJsonCtor.parameters.single.type;
36+
var asCastType = fromJsonCtor.parameters.first.type;
3737

3838
var asCast = '';
3939
if (!asCastType.isDynamic && !asCastType.isObject) {

json_serializable/test/json_serializable_test.dart

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,13 @@ abstract class _$OrderSerializerMixin {
188188
});
189189
}
190190

191+
192+
test('class with fromJson() constructor with optional parameters', () async {
193+
var output = await runForElementNamed('FromJsonOptionalParameters');
194+
195+
expect(output, contains('new ChildWithFromJson.fromJson'));
196+
});
197+
191198
test('class with child json-able object', () async {
192199
var output = await runForElementNamed('ParentObject');
193200

@@ -321,6 +328,17 @@ class FinalFields {
321328
FinalFields(this.a);
322329
}
323330
331+
@JsonSerializable()
332+
class FromJsonOptionalParameters {
333+
final ChildWithFromJson child;
334+
335+
FromJsonOptionalParameters(this.child);
336+
}
337+
338+
class ChildWithFromJson {
339+
ChildWithFromJson.fromJson(json, {initValue: false}) {}
340+
}
341+
324342
@JsonSerializable()
325343
class ParentObject {
326344
int number;

0 commit comments

Comments
 (0)