Skip to content
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

Use map syntax to clean up null handling in toJson functions #1443

Merged
merged 7 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
38 changes: 16 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.

52 changes: 17 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',
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added `middleName since it's nullable – to exercise behavior here!

)..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
1 change: 0 additions & 1 deletion json_serializable/lib/src/constants.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
const closureArg = 'e';

const generatedLocalVarName = 'val';
kevmoo marked this conversation as resolved.
Show resolved Hide resolved
const toJsonMapHelperName = 'writeNotNull';

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