Skip to content

Commit

Permalink
Use map syntax to clean up null handling in toJson functions (#1443)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevmoo authored Aug 9, 2024
1 parent 9ccbbb2 commit 55d68f4
Show file tree
Hide file tree
Showing 17 changed files with 261 additions and 461 deletions.
39 changes: 17 additions & 22 deletions _test_yaml/test/src/build_config.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

53 changes: 18 additions & 35 deletions example/lib/example.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions example/test/example_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ import 'package:test/test.dart';

void main() {
test('JsonSerializable', () {
final person = Person('Inigo', 'Montoya', DateTime(1560, 5, 5))
..orders = [Order(DateTime.now())..item = (Item()..count = 42)];
final person = Person(
'Inigo',
'Montoya',
DateTime(1560, 5, 5),
middleName: 'Bob',
)..orders = [Order(DateTime.now())..item = (Item()..count = 42)];

final personJson = loudEncode(person);

Expand Down
3 changes: 2 additions & 1 deletion json_serializable/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## 6.8.1-wip
## 6.9.0-wip

- Use conditional map syntax to clean up `null` handling in `toJson` functions.
- Require Dart 3.5

## 6.8.0
Expand Down
3 changes: 1 addition & 2 deletions json_serializable/lib/src/constants.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
/// Name used for closure argument when generating calls to `map`.
const closureArg = 'e';

const generatedLocalVarName = 'val';
const toJsonMapHelperName = 'writeNotNull';
const generatedLocalVarName = 'value';

const converterOrKeyInstructions = r'''
* Use `JsonConverter`
Expand Down
97 changes: 14 additions & 83 deletions json_serializable/lib/src/encoder_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -97,18 +97,22 @@ mixin EncodeHelper implements HelperCore {

if (config.genericArgumentFactories) _writeGenericArgumentFactories(buffer);

buffer.write(') ');
buffer
..write(') ')
..writeln('=> <String, dynamic>{')
..writeAll(accessibleFields.map((field) {
final access = _fieldAccess(field);

final canWriteAllJsonValuesWithoutNullCheck =
accessibleFields.every(_canWriteJsonWithoutNullCheck);
final keyExpression = safeNameAccess(field);
final valueExpression = _serializeField(field, access);

if (canWriteAllJsonValuesWithoutNullCheck) {
// write simple `toJson` method that includes all keys...
_writeToJsonSimple(buffer, accessibleFields);
} else {
// At least one field should be excluded if null
_writeToJsonWithNullChecks(buffer, accessibleFields);
}
final keyValuePair = _canWriteJsonWithoutNullCheck(field)
? '$keyExpression: $valueExpression'
: 'if ($valueExpression case final $generatedLocalVarName?) '
'$keyExpression: $generatedLocalVarName';
return ' $keyValuePair,\n';
}))
..writeln('};');

yield buffer.toString();
}
Expand All @@ -125,81 +129,8 @@ mixin EncodeHelper implements HelperCore {
}
}

void _writeToJsonSimple(StringBuffer buffer, Iterable<FieldElement> fields) {
buffer
..writeln('=> <String, dynamic>{')
..writeAll(fields.map((field) {
final access = _fieldAccess(field);
final value =
'${safeNameAccess(field)}: ${_serializeField(field, access)}';
return ' $value,\n';
}))
..writeln('};');
}

static const _toJsonParamName = 'instance';

void _writeToJsonWithNullChecks(
StringBuffer buffer,
Iterable<FieldElement> fields,
) {
buffer
..writeln('{')
..writeln(' final $generatedLocalVarName = <String, dynamic>{');

// Note that the map literal is left open above. As long as target fields
// don't need to be intercepted by the `only if null` logic, write them
// to the map literal directly. In theory, should allow more efficient
// serialization.
var directWrite = true;

for (final field in fields) {
var safeFieldAccess = _fieldAccess(field);
final safeJsonKeyString = safeNameAccess(field);

// If `fieldName` collides with one of the local helpers, prefix
// access with `this.`.
if (safeFieldAccess == generatedLocalVarName ||
safeFieldAccess == toJsonMapHelperName) {
safeFieldAccess = 'this.$safeFieldAccess';
}

final expression = _serializeField(field, safeFieldAccess);
if (_canWriteJsonWithoutNullCheck(field)) {
if (directWrite) {
buffer.writeln(' $safeJsonKeyString: $expression,');
} else {
buffer.writeln(
' $generatedLocalVarName[$safeJsonKeyString] = $expression;');
}
} else {
if (directWrite) {
// close the still-open map literal
buffer
..writeln(' };')
..writeln()

// write the helper to be used by all following null-excluding
// fields
..writeln('''
void $toJsonMapHelperName(String key, dynamic value) {
if (value != null) {
$generatedLocalVarName[key] = value;
}
}
''');
directWrite = false;
}
buffer.writeln(
' $toJsonMapHelperName($safeJsonKeyString, $expression);');
}
}

buffer
..writeln(' return $generatedLocalVarName;')
..writeln(' }');
}

String _serializeField(FieldElement field, String accessExpression) {
try {
return getHelperContext(field)
Expand Down
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: 6.8.1-wip
version: 6.9.0-wip
description: >-
Automatically generate code for converting to and from JSON by annotating
Dart classes.
Expand Down
1 change: 0 additions & 1 deletion json_serializable/test/custom_configuration_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,6 @@ Map<String, dynamic> _$TrivialNestedNonNullableToJson(
test('some', () async {
final output = await runForElementNamed('IncludeIfNullAll');
expect(output, isNot(contains(generatedLocalVarName)));
expect(output, isNot(contains(toJsonMapHelperName)));
});
});
}
Expand Down
69 changes: 27 additions & 42 deletions json_serializable/test/integration/converter_examples.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 55d68f4

Please sign in to comment.