Skip to content

Add disallowUnrecognizedKeys option #212

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 14 commits into from
Jun 1, 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
9 changes: 8 additions & 1 deletion json_annotation/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
## 0.2.7

* Added `JsonSerializable.disallowUnrecognizedKeys`.
* Added a helper function to support this option. This function starts with a
`$` and should only be referenced by generated code. It is not meant for
direct use.

## 0.2.6

* `CheckedFromJsonException`
Expand Down Expand Up @@ -29,7 +36,7 @@

## 0.2.2

* Added a helper class – `$JsonMapWrapper` – and helper functions – `$wrapMap`,
* Added a helper class – `$JsonMapWrapper` – and helper functions – `$wrapMap`,
`$wrapMapHandleNull`, `$wrapList`, and `$wrapListHandleNull` – to support
the `useWrappers` option added to `JsonSerializableGenerator` in `v0.3.0` of
`package:json_serializable`.
Expand Down
1 change: 1 addition & 0 deletions json_annotation/lib/json_annotation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
/// enabled.
library json_annotation;

export 'src/allowed_keys_helpers.dart';
export 'src/checked_helpers.dart';
export 'src/json_literal.dart';
export 'src/json_serializable.dart';
Expand Down
36 changes: 36 additions & 0 deletions json_annotation/lib/src/allowed_keys_helpers.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/// Helper function used in generated code when
/// `JsonSerializable.disallowUnrecognizedKeys` is `true`.
///
/// Should not be used directly.
void $checkAllowedKeys(Map map, Iterable<String> allowedKeys) {
if (map == null) return;
var invalidKeys = map.keys.where((k) => !allowedKeys.contains(k));
if (invalidKeys.isNotEmpty) {
throw new UnrecognizedKeysException(
new List<String>.from(invalidKeys), map, allowedKeys.toList());
}
}

/// Exception thrown if there is an unrecognized key in a json map that was
/// provided during deserialization.
class UnrecognizedKeysException implements Exception {
/// The allowed keys for [map].
final List<String> allowedKeys;

/// The keys from [map] that were unrecognized.
final List<String> unrecognizedKeys;

/// The source [Map] that the key was found in.
final Map map;

/// A human-readable message corresponding to the error.
String get message =>
'Unrecognized keys [${unrecognizedKeys.join(', ')}], supported keys are '
'[${allowedKeys.join(', ')}]';

UnrecognizedKeysException(this.unrecognizedKeys, this.map, this.allowedKeys);
}
12 changes: 10 additions & 2 deletions json_annotation/lib/src/checked_helpers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'allowed_keys_helpers.dart';

/// Helper function used in generated code when
/// `JsonSerializableGenerator.checked` is `true`.
///
Expand Down Expand Up @@ -85,6 +87,12 @@ class CheckedFromJsonException implements Exception {
: _className = className,
message = _getMessage(innerError);

static String _getMessage(Object error) =>
(error is ArgumentError) ? error.message?.toString() : null;
static String _getMessage(Object error) {
if (error is ArgumentError) {
return error.message?.toString();
} else if (error is UnrecognizedKeysException) {
return error.message;
}
return null;
}
}
12 changes: 10 additions & 2 deletions json_annotation/lib/src/json_serializable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@

/// An annotation used to specify a class to generate code for.
class JsonSerializable {
/// If `false` (the default), then any unrecognized keys passed to the
/// generated FromJson factory will be ignored.
///
/// If `true`, any unrecognized keys will be treated as an error.
final bool disallowUnrecognizedKeys;

/// If `true` (the default), a private, static `_$ExampleFromJson` method
/// is created in the generated part file.
///
Expand Down Expand Up @@ -48,11 +54,13 @@ class JsonSerializable {

/// Creates a new [JsonSerializable] instance.
const JsonSerializable(
{bool createFactory: true,
{bool disallowUnrecognizedKeys: false,
bool createFactory: true,
bool createToJson: true,
bool includeIfNull: true,
bool nullable: true})
: this.createFactory = createFactory ?? true,
: this.disallowUnrecognizedKeys = disallowUnrecognizedKeys ?? false,
this.createFactory = createFactory ?? true,
this.createToJson = createToJson ?? true,
this.includeIfNull = includeIfNull ?? true,
this.nullable = nullable ?? true;
Expand Down
2 changes: 1 addition & 1 deletion json_annotation/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: json_annotation
version: 0.2.6
version: 0.2.7-dev
description: >-
Classes and helper functions that support JSON code generation via the
`json_serializable` package.
Expand Down
13 changes: 11 additions & 2 deletions json_serializable/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
## 0.5.6

* Added support for `JsonSerializable.disallowUnrecognizedKeys`.
Copy link
Collaborator

Choose a reason for hiding this comment

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

Put runtime info here from json_annotation

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

done

Copy link
Collaborator

Choose a reason for hiding this comment

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

Also note that fromJson functions now use block syntax

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

done

* Throws an `UnrecognizedKeysException` if it finds unrecognized keys in the
JSON map used to create the annotated object.
* Will be captured captured and wrapped in a `CheckedFromJsonException` if
`checked` is enabled in `json_serializable`.
* All `fromJson` constructors now use block syntax instead of fat arrows.

## 0.5.5

* Added support for `JsonKey.defaultValue`.
Expand Down Expand Up @@ -35,9 +44,9 @@

* If `JsonKey.fromJson` function parameter is `Iterable` or `Map` with type
arguments of `dynamic` or `Object`, omit the arguments when generating a
cast.
cast.
`_myHelper(json['key'] as Map)` instead of
`_myHelper(json['key'] as Map<dynamic, dynamic>)`.
`_myHelper(json['key'] as Map<dynamic, dynamic>)`.

* `JsonKey.fromJson`/`.toJson` now support functions with optional arguments.

Expand Down
10 changes: 6 additions & 4 deletions json_serializable/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ Building creates the corresponding part `example.g.dart`:
```dart
part of 'example.dart';

Person _$PersonFromJson(Map<String, dynamic> json) => new Person(
firstName: json['firstName'] as String,
lastName: json['lastName'] as String,
dateOfBirth: DateTime.parse(json['dateOfBirth'] as String));
Person _$PersonFromJson(Map<String, dynamic> json) {
return new Person(
firstName: json['firstName'] as String,
lastName: json['lastName'] as String,
dateOfBirth: DateTime.parse(json['dateOfBirth'] as String));
}

abstract class _$PersonSerializerMixin {
String get firstName;
Expand Down
10 changes: 6 additions & 4 deletions json_serializable/example/example.g.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ part of 'example.dart';
// Generator: JsonSerializableGenerator
// **************************************************************************

Person _$PersonFromJson(Map<String, dynamic> json) => new Person(
firstName: json['firstName'] as String,
lastName: json['lastName'] as String,
dateOfBirth: DateTime.parse(json['dateOfBirth'] as String));
Person _$PersonFromJson(Map<String, dynamic> json) {
return new Person(
firstName: json['firstName'] as String,
lastName: json['lastName'] as String,
dateOfBirth: DateTime.parse(json['dateOfBirth'] as String));
}

abstract class _$PersonSerializerMixin {
String get firstName;
Expand Down
71 changes: 41 additions & 30 deletions json_serializable/lib/src/generator_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ class _GeneratorHelper {
var mapType = _generator.anyMap ? 'Map' : 'Map<String, dynamic>';
_buffer.write('$_targetClassReference '
'${_prefix}FromJson${_genericClassArguments(true)}'
'($mapType json) =>');
'($mapType json) {\n');

String deserializeFun(String paramOrFieldName,
{ParameterElement ctorParam}) =>
Expand All @@ -152,10 +152,11 @@ class _GeneratorHelper {
if (_generator.checked) {
var classLiteral = escapeDartString(_element.name);

_buffer.write(''' \$checkedNew(
_buffer.write('''
return \$checkedNew(
$classLiteral,
json,
()''');
() {''');

var data = writeConstructorInvocation(
_element,
Expand All @@ -169,31 +170,28 @@ class _GeneratorHelper {

fieldsSetByFactory = data.usedCtorParamsAndFields;

if (data.fieldsToSet.isEmpty) {
// Use simple arrow syntax for the constructor invocation.
// There are no fields to set
_buffer.write(' => ${data.content}');
} else {
// If there are fields to set, create a full function body and
// create a temporary variable to hold the instance so we can make
// wrapped calls to all of the fields value assignments.
_buffer.write(''' {
var val = ''');
_buffer.write(data.content);
_buffer.writeln(';');

for (var field in data.fieldsToSet) {
_buffer.writeln();
var safeName = _safeNameAccess(accessibleFields[field]);
_buffer.write('''
if (_annotation.disallowUnrecognizedKeys) {
var listLiteral = jsonLiteralAsDart(
accessibleFields.values.map(_nameAccess).toList(), true);
_buffer.write('''
\$checkAllowedKeys(json, $listLiteral);''');
}
_buffer.write('''
var val = ${data.content};''');

for (var field in data.fieldsToSet) {
_buffer.writeln();
var safeName = _safeNameAccess(accessibleFields[field]);
_buffer.write('''
\$checkedConvert(json, $safeName, (v) => ''');
_buffer.write('val.$field = ');
_buffer.write(_deserializeForField(accessibleFields[field],
checkedProperty: true));
_buffer.write(');');
}
_buffer.writeln('return val; }');
_buffer.write('val.$field = ');
_buffer.write(_deserializeForField(accessibleFields[field],
checkedProperty: true));
_buffer.write(');');
}

_buffer.writeln('return val; }');

var fieldKeyMap = new Map.fromEntries(fieldsSetByFactory
.map((k) => new MapEntry(k, _nameAccess(accessibleFields[k])))
.where((me) => me.key != me.value));
Expand All @@ -206,7 +204,9 @@ class _GeneratorHelper {
fieldKeyMapArg = ', fieldKeyMap: $mapLiteral';
}

_buffer.write('$fieldKeyMapArg)');
_buffer.write(fieldKeyMapArg);

_buffer.write(')');
} else {
var data = writeConstructorInvocation(
_element,
Expand All @@ -220,14 +220,25 @@ class _GeneratorHelper {

fieldsSetByFactory = data.usedCtorParamsAndFields;

_buffer.write(' ${data.content}');
if (_annotation.disallowUnrecognizedKeys) {
var listLiteral = jsonLiteralAsDart(
fieldsSetByFactory
.map((k) => _nameAccess(accessibleFields[k]))
.toList(),
true);
_buffer.write('''
\$checkAllowedKeys(json, $listLiteral);''');
}

_buffer.write('''
return ${data.content}''');
for (var field in data.fieldsToSet) {
_buffer.writeln();
_buffer.write(' ..$field = ');
_buffer.write(' ..$field = ');
_buffer.write(deserializeFun(field));
}
}
_buffer.writeln(';');
_buffer.writeln(';\n}');
_buffer.writeln();

// If there are fields that are final – that are not set via the generated
Expand Down
2 changes: 2 additions & 0 deletions json_serializable/lib/src/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import 'package:source_gen/source_gen.dart';

JsonSerializable valueForAnnotation(ConstantReader annotation) =>
new JsonSerializable(
disallowUnrecognizedKeys:
annotation.read('disallowUnrecognizedKeys').boolValue,
createToJson: annotation.read('createToJson').boolValue,
createFactory: annotation.read('createFactory').boolValue,
nullable: annotation.read('nullable').boolValue,
Expand Down
8 changes: 6 additions & 2 deletions json_serializable/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: json_serializable
version: 0.5.5
version: 0.5.6-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 All @@ -12,7 +12,7 @@ dependencies:

# Use a tight version constraint to ensure that a constraint on
# `json_annotation`. Properly constrains all features it provides.
json_annotation: '>=0.2.6 <0.2.7'
json_annotation: '>=0.2.7 <0.2.8'
Copy link
Collaborator

Choose a reason for hiding this comment

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

Don't you need a dep override to make tests run?

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 back - this got removed when I merged master (I didn't have to add it originally so it wasn't a merge conflict.... source control is fun)

Copy link
Collaborator

Choose a reason for hiding this comment

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

ack

meta: ^1.1.0
path: ^1.3.2
source_gen: '>=0.8.1 <0.9.0'
Expand All @@ -25,3 +25,7 @@ dev_dependencies:
logging: ^0.11.3+1
test: ^0.12.3
yaml: ^2.1.13

dependency_overrides:
json_annotation:
path: ../json_annotation
Loading