From e51f25ebe045988b9a8fac6a88bf7f9263fe96ea Mon Sep 17 00:00:00 2001 From: Rob Becker Date: Mon, 31 Jul 2023 12:22:13 -0600 Subject: [PATCH 1/2] include json packages (#11) * Add json_annotation_3_1_1 package * fix multiple build artifacts separator * publish renamed json_serializable_3_5_2 package * use hosted syntax, remove pub gets --- Dockerfile | 8 +- json_annotation-3.1.1/.gitignore | 4 + json_annotation-3.1.1/CHANGELOG.md | 174 ++ json_annotation-3.1.1/LICENSE | 26 + json_annotation-3.1.1/README.md | 14 + .../lib/json_annotation.dart | 19 + .../lib/src/allowed_keys_helpers.dart | 99 + .../lib/src/checked_helpers.dart | 131 ++ .../lib/src/json_converter.dart | 14 + json_annotation-3.1.1/lib/src/json_key.dart | 121 ++ .../lib/src/json_literal.dart | 29 + .../lib/src/json_serializable.dart | 243 +++ .../lib/src/json_serializable.g.dart | 108 + json_annotation-3.1.1/lib/src/json_value.dart | 13 + json_annotation-3.1.1/mono_pkg.yaml | 10 + json_annotation-3.1.1/pubspec.yaml | 13 + json_serializable-3.5.2/CHANGELOG.md | 627 ++++++ json_serializable-3.5.2/LICENSE | 26 + json_serializable-3.5.2/README.md | 160 ++ json_serializable-3.5.2/build.yaml | 115 + json_serializable-3.5.2/dart_test.yaml | 3 + json_serializable-3.5.2/doc/doc.md | 43 + json_serializable-3.5.2/example/example.dart | 17 + .../example/example.g.dart | 21 + json_serializable-3.5.2/lib/builder.dart | 44 + .../lib/json_serializable.dart | 6 + .../lib/src/constants.dart | 9 + .../lib/src/decode_helper.dart | 323 +++ .../lib/src/encoder_helper.dart | 156 ++ .../lib/src/field_helpers.dart | 111 + .../lib/src/generator_helper.dart | 117 + .../lib/src/helper_core.dart | 156 ++ .../lib/src/json_key_utils.dart | 279 +++ .../lib/src/json_literal_generator.dart | 100 + .../lib/src/json_part_builder.dart | 32 + .../lib/src/json_serializable_generator.dart | 75 + .../lib/src/lambda_result.dart | 18 + json_serializable-3.5.2/lib/src/settings.dart | 74 + .../lib/src/shared_checkers.dart | 85 + .../lib/src/type_helper.dart | 92 + .../lib/src/type_helper_ctx.dart | 161 ++ .../lib/src/type_helpers/big_int_helper.dart | 28 + .../lib/src/type_helpers/convert_helper.dart | 64 + .../src/type_helpers/date_time_helper.dart | 29 + .../lib/src/type_helpers/duration_helper.dart | 53 + .../lib/src/type_helpers/enum_helper.dart | 120 + .../type_helpers/generic_factory_helper.dart | 50 + .../lib/src/type_helpers/iterable_helper.dart | 102 + .../type_helpers/json_converter_helper.dart | 219 ++ .../lib/src/type_helpers/json_helper.dart | 284 +++ .../lib/src/type_helpers/map_helper.dart | 167 ++ .../lib/src/type_helpers/to_from_string.dart | 82 + .../lib/src/type_helpers/uri_helper.dart | 28 + .../lib/src/type_helpers/value_helper.dart | 48 + .../lib/src/unsupported_type_error.dart | 17 + json_serializable-3.5.2/lib/src/utils.dart | 273 +++ json_serializable-3.5.2/lib/type_helper.dart | 19 + json_serializable-3.5.2/mono_pkg.yaml | 23 + json_serializable-3.5.2/pubspec.yaml | 37 + json_serializable-3.5.2/test/config_test.dart | 146 ++ .../test/custom_configuration_test.dart | 222 ++ .../test/default_value/default_value.dart | 65 + .../test/default_value/default_value.g.dart | 102 + .../default_value.g_any_map__checked.dart | 68 + .../default_value.g_any_map__checked.g.dart | 124 ++ .../default_value_interface.dart | 24 + .../default_value/default_value_test.dart | 64 + .../test/ensure_build_test.dart | 13 + .../test/enum_helper_test.dart | 34 + .../generic_argument_factories.dart | 49 + .../generic_argument_factories.g.dart | 59 + .../test/generic_files/generic_class.dart | 104 + .../test/generic_files/generic_class.g.dart | 63 + .../test/generic_files/generic_test.dart | 118 + .../test/integration/integration_test.dart | 283 +++ .../test/integration/json_test_common.dart | 97 + .../test/integration/json_test_example.dart | 196 ++ .../test/integration/json_test_example.g.dart | 236 ++ .../json_test_example.g_any_map.dart | 206 ++ .../json_test_example.g_any_map.g.dart | 246 +++ .../json_test_example.g_non_nullable.dart | 206 ++ .../json_test_example.g_non_nullable.g.dart | 203 ++ .../test/json_serializable_test.dart | 117 + .../test/kitchen_sink/json_converters.dart | 67 + .../test/kitchen_sink/kitchen_sink.dart | 193 ++ .../kitchen_sink/kitchen_sink.factories.dart | 21 + .../test/kitchen_sink/kitchen_sink.g.dart | 187 ++ .../kitchen_sink/kitchen_sink.g_any_map.dart | 197 ++ .../kitchen_sink.g_any_map.g.dart | 184 ++ ...sink.g_any_map__checked__non_nullable.dart | 203 ++ ...nk.g_any_map__checked__non_nullable.g.dart | 234 ++ .../kitchen_sink.g_any_map__non_nullable.dart | 200 ++ ...itchen_sink.g_any_map__non_nullable.g.dart | 168 ++ .../kitchen_sink.g_exclude_null.dart | 199 ++ .../kitchen_sink.g_exclude_null.g.dart | 222 ++ ...hen_sink.g_exclude_null__non_nullable.dart | 202 ++ ...n_sink.g_exclude_null__non_nullable.g.dart | 189 ++ .../kitchen_sink.g_explicit_to_json.dart | 199 ++ .../kitchen_sink.g_explicit_to_json.g.dart | 187 ++ .../kitchen_sink.g_non_nullable.dart | 199 ++ .../kitchen_sink.g_non_nullable.g.dart | 171 ++ .../kitchen_sink/kitchen_sink_interface.dart | 106 + .../test/kitchen_sink/kitchen_sink_test.dart | 430 ++++ .../test/kitchen_sink/simple_object.dart | 18 + .../test/kitchen_sink/simple_object.g.dart | 18 + .../test/kitchen_sink/strict_keys_object.dart | 23 + .../kitchen_sink/strict_keys_object.g.dart | 23 + .../literal/big-list-of-naughty-strings.json | 509 +++++ .../test/literal/json_literal.dart | 17 + .../test/literal/json_literal.g.dart | 603 +++++ .../test/literal/json_literal.json | 42 + .../test/literal/json_literal_test.dart | 39 + json_serializable-3.5.2/test/readme_test.dart | 63 + .../test/shared_config.dart | 25 + .../src/_json_serializable_test_input.dart | 583 +++++ .../test/src/checked_test_input.dart | 52 + .../test/src/core_subclass_type_input.dart | 81 + .../test/src/default_value_input.dart | 184 ++ .../test/src/field_namer_input.dart | 61 + .../test/src/generic_test_input.dart | 87 + .../test/src/inheritance_test_input.dart | 138 ++ .../test/src/json_converter_test_input.dart | 194 ++ .../test/src/map_key_variety_test_input.dart | 19 + .../test/src/setter_test_input.dart | 46 + .../test/src/to_from_json_test_input.dart | 240 ++ .../src/unknown_enum_value_test_input.dart | 120 + .../test/supported_types/enum_type.dart | 5 + .../test/supported_types/input.dart | 28 + .../test/supported_types/input.g.dart | 21 + .../supported_types/input.type_bigint.dart | 25 + .../supported_types/input.type_bigint.g.dart | 20 + .../test/supported_types/input.type_bool.dart | 28 + .../supported_types/input.type_bool.g.dart | 21 + .../supported_types/input.type_datetime.dart | 25 + .../input.type_datetime.g.dart | 20 + .../supported_types/input.type_double.dart | 28 + .../supported_types/input.type_double.g.dart | 21 + .../supported_types/input.type_duration.dart | 25 + .../input.type_duration.g.dart | 20 + .../supported_types/input.type_enumtype.dart | 29 + .../input.type_enumtype.g.dart | 62 + .../test/supported_types/input.type_int.dart | 28 + .../supported_types/input.type_int.g.dart | 21 + .../supported_types/input.type_iterable.dart | 245 +++ .../input.type_iterable.g.dart | 224 ++ .../test/supported_types/input.type_list.dart | 245 +++ .../supported_types/input.type_list.g.dart | 233 ++ .../test/supported_types/input.type_map.dart | 1757 +++++++++++++++ .../supported_types/input.type_map.g.dart | 1931 +++++++++++++++++ .../test/supported_types/input.type_num.dart | 28 + .../supported_types/input.type_num.g.dart | 21 + .../supported_types/input.type_object.dart | 25 + .../supported_types/input.type_object.g.dart | 20 + .../test/supported_types/input.type_set.dart | 245 +++ .../supported_types/input.type_set.g.dart | 234 ++ .../supported_types/input.type_string.dart | 28 + .../supported_types/input.type_string.g.dart | 21 + .../test/supported_types/input.type_uri.dart | 25 + .../supported_types/input.type_uri.g.dart | 20 + .../type_test.bigint_test.dart | 41 + .../supported_types/type_test.bool_test.dart | 43 + .../test/supported_types/type_test.dart | 43 + .../type_test.datetime_test.dart | 41 + .../type_test.double_test.dart | 43 + .../type_test.duration_test.dart | 41 + .../type_test.enumtype_test.dart | 43 + .../supported_types/type_test.int_test.dart | 43 + .../type_test.iterable_test.dart | 43 + .../supported_types/type_test.list_test.dart | 43 + .../supported_types/type_test.map_test.dart | 43 + .../supported_types/type_test.num_test.dart | 43 + .../type_test.object_test.dart | 41 + .../supported_types/type_test.set_test.dart | 43 + .../type_test.string_test.dart | 43 + .../supported_types/type_test.uri_test.dart | 41 + .../test/test_sources/test_sources.dart | 81 + json_serializable-3.5.2/test/test_utils.dart | 39 + json_serializable-3.5.2/test/utils_test.dart | 53 + json_serializable-3.5.2/tool/doc_builder.dart | 191 ++ json_serializable-3.5.2/tool/shared.dart | 71 + .../tool/test_builder.dart | 208 ++ .../tool/test_type_builder.dart | 172 ++ .../tool/test_type_data.dart | 152 ++ 183 files changed, 22880 insertions(+), 1 deletion(-) create mode 100644 json_annotation-3.1.1/.gitignore create mode 100644 json_annotation-3.1.1/CHANGELOG.md create mode 100644 json_annotation-3.1.1/LICENSE create mode 100644 json_annotation-3.1.1/README.md create mode 100644 json_annotation-3.1.1/lib/json_annotation.dart create mode 100644 json_annotation-3.1.1/lib/src/allowed_keys_helpers.dart create mode 100644 json_annotation-3.1.1/lib/src/checked_helpers.dart create mode 100644 json_annotation-3.1.1/lib/src/json_converter.dart create mode 100644 json_annotation-3.1.1/lib/src/json_key.dart create mode 100644 json_annotation-3.1.1/lib/src/json_literal.dart create mode 100644 json_annotation-3.1.1/lib/src/json_serializable.dart create mode 100644 json_annotation-3.1.1/lib/src/json_serializable.g.dart create mode 100644 json_annotation-3.1.1/lib/src/json_value.dart create mode 100644 json_annotation-3.1.1/mono_pkg.yaml create mode 100644 json_annotation-3.1.1/pubspec.yaml create mode 100644 json_serializable-3.5.2/CHANGELOG.md create mode 100644 json_serializable-3.5.2/LICENSE create mode 100644 json_serializable-3.5.2/README.md create mode 100644 json_serializable-3.5.2/build.yaml create mode 100644 json_serializable-3.5.2/dart_test.yaml create mode 100644 json_serializable-3.5.2/doc/doc.md create mode 100644 json_serializable-3.5.2/example/example.dart create mode 100644 json_serializable-3.5.2/example/example.g.dart create mode 100644 json_serializable-3.5.2/lib/builder.dart create mode 100644 json_serializable-3.5.2/lib/json_serializable.dart create mode 100644 json_serializable-3.5.2/lib/src/constants.dart create mode 100644 json_serializable-3.5.2/lib/src/decode_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/encoder_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/field_helpers.dart create mode 100644 json_serializable-3.5.2/lib/src/generator_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/helper_core.dart create mode 100644 json_serializable-3.5.2/lib/src/json_key_utils.dart create mode 100644 json_serializable-3.5.2/lib/src/json_literal_generator.dart create mode 100644 json_serializable-3.5.2/lib/src/json_part_builder.dart create mode 100644 json_serializable-3.5.2/lib/src/json_serializable_generator.dart create mode 100644 json_serializable-3.5.2/lib/src/lambda_result.dart create mode 100644 json_serializable-3.5.2/lib/src/settings.dart create mode 100644 json_serializable-3.5.2/lib/src/shared_checkers.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helper_ctx.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/big_int_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/convert_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/date_time_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/duration_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/enum_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/generic_factory_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/iterable_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/json_converter_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/json_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/map_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/to_from_string.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/uri_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/type_helpers/value_helper.dart create mode 100644 json_serializable-3.5.2/lib/src/unsupported_type_error.dart create mode 100644 json_serializable-3.5.2/lib/src/utils.dart create mode 100644 json_serializable-3.5.2/lib/type_helper.dart create mode 100644 json_serializable-3.5.2/mono_pkg.yaml create mode 100644 json_serializable-3.5.2/pubspec.yaml create mode 100644 json_serializable-3.5.2/test/config_test.dart create mode 100644 json_serializable-3.5.2/test/custom_configuration_test.dart create mode 100644 json_serializable-3.5.2/test/default_value/default_value.dart create mode 100644 json_serializable-3.5.2/test/default_value/default_value.g.dart create mode 100644 json_serializable-3.5.2/test/default_value/default_value.g_any_map__checked.dart create mode 100644 json_serializable-3.5.2/test/default_value/default_value.g_any_map__checked.g.dart create mode 100644 json_serializable-3.5.2/test/default_value/default_value_interface.dart create mode 100644 json_serializable-3.5.2/test/default_value/default_value_test.dart create mode 100644 json_serializable-3.5.2/test/ensure_build_test.dart create mode 100644 json_serializable-3.5.2/test/enum_helper_test.dart create mode 100644 json_serializable-3.5.2/test/generic_files/generic_argument_factories.dart create mode 100644 json_serializable-3.5.2/test/generic_files/generic_argument_factories.g.dart create mode 100644 json_serializable-3.5.2/test/generic_files/generic_class.dart create mode 100644 json_serializable-3.5.2/test/generic_files/generic_class.g.dart create mode 100644 json_serializable-3.5.2/test/generic_files/generic_test.dart create mode 100644 json_serializable-3.5.2/test/integration/integration_test.dart create mode 100644 json_serializable-3.5.2/test/integration/json_test_common.dart create mode 100644 json_serializable-3.5.2/test/integration/json_test_example.dart create mode 100644 json_serializable-3.5.2/test/integration/json_test_example.g.dart create mode 100644 json_serializable-3.5.2/test/integration/json_test_example.g_any_map.dart create mode 100644 json_serializable-3.5.2/test/integration/json_test_example.g_any_map.g.dart create mode 100644 json_serializable-3.5.2/test/integration/json_test_example.g_non_nullable.dart create mode 100644 json_serializable-3.5.2/test/integration/json_test_example.g_non_nullable.g.dart create mode 100644 json_serializable-3.5.2/test/json_serializable_test.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/json_converters.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.factories.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map.g.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__checked__non_nullable.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__checked__non_nullable.g.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__non_nullable.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__non_nullable.g.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null.g.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null__non_nullable.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null__non_nullable.g.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_explicit_to_json.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_explicit_to_json.g.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_non_nullable.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_non_nullable.g.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink_interface.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/kitchen_sink_test.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/simple_object.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/simple_object.g.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/strict_keys_object.dart create mode 100644 json_serializable-3.5.2/test/kitchen_sink/strict_keys_object.g.dart create mode 100644 json_serializable-3.5.2/test/literal/big-list-of-naughty-strings.json create mode 100644 json_serializable-3.5.2/test/literal/json_literal.dart create mode 100644 json_serializable-3.5.2/test/literal/json_literal.g.dart create mode 100644 json_serializable-3.5.2/test/literal/json_literal.json create mode 100644 json_serializable-3.5.2/test/literal/json_literal_test.dart create mode 100644 json_serializable-3.5.2/test/readme_test.dart create mode 100644 json_serializable-3.5.2/test/shared_config.dart create mode 100644 json_serializable-3.5.2/test/src/_json_serializable_test_input.dart create mode 100644 json_serializable-3.5.2/test/src/checked_test_input.dart create mode 100644 json_serializable-3.5.2/test/src/core_subclass_type_input.dart create mode 100644 json_serializable-3.5.2/test/src/default_value_input.dart create mode 100644 json_serializable-3.5.2/test/src/field_namer_input.dart create mode 100644 json_serializable-3.5.2/test/src/generic_test_input.dart create mode 100644 json_serializable-3.5.2/test/src/inheritance_test_input.dart create mode 100644 json_serializable-3.5.2/test/src/json_converter_test_input.dart create mode 100644 json_serializable-3.5.2/test/src/map_key_variety_test_input.dart create mode 100644 json_serializable-3.5.2/test/src/setter_test_input.dart create mode 100644 json_serializable-3.5.2/test/src/to_from_json_test_input.dart create mode 100644 json_serializable-3.5.2/test/src/unknown_enum_value_test_input.dart create mode 100644 json_serializable-3.5.2/test/supported_types/enum_type.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_bigint.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_bigint.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_bool.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_bool.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_datetime.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_datetime.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_double.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_double.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_duration.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_duration.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_enumtype.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_enumtype.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_int.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_int.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_iterable.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_iterable.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_list.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_list.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_map.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_map.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_num.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_num.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_object.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_object.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_set.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_set.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_string.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_string.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_uri.dart create mode 100644 json_serializable-3.5.2/test/supported_types/input.type_uri.g.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.bigint_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.bool_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.datetime_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.double_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.duration_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.enumtype_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.int_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.iterable_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.list_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.map_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.num_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.object_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.set_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.string_test.dart create mode 100644 json_serializable-3.5.2/test/supported_types/type_test.uri_test.dart create mode 100644 json_serializable-3.5.2/test/test_sources/test_sources.dart create mode 100644 json_serializable-3.5.2/test/test_utils.dart create mode 100644 json_serializable-3.5.2/test/utils_test.dart create mode 100644 json_serializable-3.5.2/tool/doc_builder.dart create mode 100644 json_serializable-3.5.2/tool/shared.dart create mode 100644 json_serializable-3.5.2/tool/test_builder.dart create mode 100644 json_serializable-3.5.2/tool/test_type_builder.dart create mode 100644 json_serializable-3.5.2/tool/test_type_data.dart diff --git a/Dockerfile b/Dockerfile index c1d81d3e2..b4191322b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -27,6 +27,12 @@ WORKDIR /build/dio RUN timeout 5m dart pub get RUN create_publishable_artifact.sh -ARG BUILD_ARTIFACTS_PUB=/build/dio/pub_package.pub.tgz +WORKDIR /build/json_annotation-3.1.1 +RUN create_publishable_artifact.sh + +WORKDIR /build/json_serializable-3.5.2 +RUN create_publishable_artifact.sh + +ARG BUILD_ARTIFACTS_PUB=/build/dio/pub_package.pub.tgz:/build/json_annotation-3.1.1/pub_package.pub.tgz:/build/json_serializable-3.5.2/pub_package.pub.tgz FROM scratch \ No newline at end of file diff --git a/json_annotation-3.1.1/.gitignore b/json_annotation-3.1.1/.gitignore new file mode 100644 index 000000000..211ec1c68 --- /dev/null +++ b/json_annotation-3.1.1/.gitignore @@ -0,0 +1,4 @@ +# Files and directories created by pub +.packages +.pub/ +pubspec.lock diff --git a/json_annotation-3.1.1/CHANGELOG.md b/json_annotation-3.1.1/CHANGELOG.md new file mode 100644 index 000000000..be64d02a6 --- /dev/null +++ b/json_annotation-3.1.1/CHANGELOG.md @@ -0,0 +1,174 @@ +## 3.1.1 + +- Avoid `null` values for `CheckedFromJsonException.message` by using + `toString()` with unrecognized error types. +- Added a helpful `UnrecognizedKeysException.toString()`. +- Fixed doc comments for `JsonSerializable.genericArgumentFactories`. + +## 3.1.0 + +- Added `JsonSerializable.genericArgumentFactories` field. +- Require at least Dart `2.7.0`. + +## 3.0.1 + +- Require at least Dart `2.6.0`. +- Fix lint that was affecting `pub.dev` score. + +## 3.0.0 + +- **BREAKING** Removed `JsonSerializable.useWrappers` and associated + `$`-prefixed helpers. +- **BREAKING** Removed `JsonSerializable.generateToJsonFunction`. +- **BREAKING** Removed `encodeEmptyCollection` from `JsonSerializable` and + `JsonKey`. +- Added `JsonSerializable.ignoreUnannotated`. +- Added `JsonKey.unknownEnumValue`. +- Require at least Dart `2.3.0`. + +## 2.4.0 + +- Deprecate members that will be removed in `json_annotation` `3.0.0` and that + are not supported in `json_serializable` `3.0.0`. + - `JsonSerializable.useWrappers` and associated `$`-prefixed helpers + - `JsonSerializable.generateToJsonFunction`, + - `encodeEmptyCollection` from `JsonSerializable` and `JsonKey`. + +## 2.3.0 + +- Added `pascal` as an additional `fieldRename` option. +- Require at least Dart `2.2.0`. + +## 2.2.0 + +* Add an optional (named) `badKey` parameter and field to + `CheckedFromJsonException`. + +## 2.1.0 + +* Require at least Dart `2.1.1`. + +* Added to `encodeEmptyCollection` to `JsonKey` and `JsonSerializable`. + +* `JsonSerializable.fromJson` now throws `CheckedFromJsonException` on errors. + This is potentially a breaking change. + +* Added a more helpful `toString` to `CheckedFromJsonException`. + +## 2.0.0 + +* **Potentially Breaking** `JsonSerializable` no longer sets default values for + fields when constructor arguments are unset or `null`. This is not likely an + issue for developers using this class as an annotation with a compatible + version of `package:json_serializable`, but it may cause issues if class is + used in other contexts. + +* Support all `build.yaml` configuration options on classes by adding a number + of fields to `JsonSerializable`: `anyMap`, `checked`, `explicitToJson`, + `generateToJsonFunction`, and `useWrappers`. + +## 1.2.0 + +* Added `JsonConverter` class to support custom conversion of types. + +## 1.1.0 + +* Added the `fieldRename` option to `JsonSerializable` and the associated + `FieldRename` enum. + +## 1.0.0 + +* Added `JsonValue` class for annotating `enum` fields with a custom + serialization value. + +* Removed `$checkAllowedKeys`, `$enumDecode` and `$enumDecodeNullable` which are + no longer needed by the latest release of `package:json_serializable`. + +## 0.2.9+1 + +* Support the Dart 2.0 stable release. + +## 0.2.9 + +* When `FormatException` is caught in "checked mode", use the `message` + property when creating `CheckedFromJsonException`. + +## 0.2.8 + +* Added `$checkKeys` helper function and deprecated `$checkAllowedKeys`. + Upgrading to the latest `json_serializable` and re-running your build will + eliminate any `@deprecated` hints you see. + +* Added `BadKeyException` exception which is the abstract super class for + `MissingRequiredKeysException`, `UnrecognizedKeysException`, and + `DisallowedNullValueException`. + +* Added `JsonKey.required` field and an associated + `MissingRequiredKeysException` that is thrown when `required` fields don't + have corresponding keys in a source JSON map. + +* Added `JsonKey.disallowNullValue` field and an associated + `DisallowedNullValueException` that is thrown when corresponding keys exist in + a source JSON map, but their values are `null`. + +* Updated documentation of `JsonSerializable.createToJson` to include details + of the new `generate_to_json_function` configuration option. + +## 0.2.7+1 + +* Small improvement to `UnrecognizedKeysException.message` output and + documentation comments. + +## 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. + * Added `UnrecognizedKeysException` for reporting errors. + +## 0.2.6 + +* `CheckedFromJsonException` + * Added a public constructor to support hand-written JSON decoding logic. + * The `message` property is now `String` (instead of `Object`). + +* Added `JsonKey.defaultValue`. + +* Added helpers for deserialization of `enum` values. + These functions starting with `$` are referenced by generated code. + They are not meant for direct use. + +## 0.2.5 + +* Added `CheckedFromJsonException` which is thrown by code generated when + `checked` is enabled in `json_serializable`. + +* Added functions to support the `checked` generation option. + These functions starting with `$` are referenced by generated code. + They are not meant for direct use. + +## 0.2.4 + +* Added `fromJson` and `toJson` fields to `JsonKey` class. + +## 0.2.3 + +* Added `ignore` field to `JsonKey` class annotation + +## 0.2.2 + +* 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`. + +## 0.2.1 + +* `JsonSerializable` class annotation + * Added `nullable` field. + * Fixed doc comment. + +## 0.2.0 + +* Moved annotation classes for `JsonSerializable` and `JsonLiteral`. diff --git a/json_annotation-3.1.1/LICENSE b/json_annotation-3.1.1/LICENSE new file mode 100644 index 000000000..389ce9856 --- /dev/null +++ b/json_annotation-3.1.1/LICENSE @@ -0,0 +1,26 @@ +Copyright 2017, the Dart project authors. All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/json_annotation-3.1.1/README.md b/json_annotation-3.1.1/README.md new file mode 100644 index 000000000..001334db6 --- /dev/null +++ b/json_annotation-3.1.1/README.md @@ -0,0 +1,14 @@ +[![Pub Package](https://img.shields.io/pub/v/json_annotation.svg)](https://pub.dev/packages/json_annotation) + +Defines the annotations used by [json_serializable] to create code for JSON +serialization and deserialization. + +See the [example] to understand how to configure your package. + +## Features and bugs + +Please file feature requests and bugs at the [issue tracker][tracker]. + +[example]: https://github.com/google/json_serializable.dart/tree/master/example +[tracker]: https://github.com/google/json_serializable.dart/issues +[json_serializable]: https://pub.dev/packages/json_serializable diff --git a/json_annotation-3.1.1/lib/json_annotation.dart b/json_annotation-3.1.1/lib/json_annotation.dart new file mode 100644 index 000000000..9d1c39706 --- /dev/null +++ b/json_annotation-3.1.1/lib/json_annotation.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2017, 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. + +/// Provides annotation classes to use with +/// [json_serializable](https://pub.dev/packages/json_serializable). +/// +/// Also contains helper functions and classes – prefixed with `$` used by +/// `json_serializable` when the `use_wrappers` or `checked` options are +/// enabled. +library json_annotation; + +export 'src/allowed_keys_helpers.dart'; +export 'src/checked_helpers.dart'; +export 'src/json_converter.dart'; +export 'src/json_key.dart'; +export 'src/json_literal.dart'; +export 'src/json_serializable.dart'; +export 'src/json_value.dart'; diff --git a/json_annotation-3.1.1/lib/src/allowed_keys_helpers.dart b/json_annotation-3.1.1/lib/src/allowed_keys_helpers.dart new file mode 100644 index 000000000..b3b9490f6 --- /dev/null +++ b/json_annotation-3.1.1/lib/src/allowed_keys_helpers.dart @@ -0,0 +1,99 @@ +// 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 `fromJson` code when +/// `JsonSerializable.disallowUnrecognizedKeys` is true for an annotated type or +/// `JsonKey.required` is `true` for any annotated fields. +/// +/// Should not be used directly. +void $checkKeys(Map map, + {List allowedKeys, + List requiredKeys, + List disallowNullValues}) { + if (map != null && allowedKeys != null) { + final invalidKeys = + map.keys.cast().where((k) => !allowedKeys.contains(k)).toList(); + if (invalidKeys.isNotEmpty) { + throw UnrecognizedKeysException(invalidKeys, map, allowedKeys); + } + } + + if (requiredKeys != null) { + final missingKeys = + requiredKeys.where((k) => !map.keys.contains(k)).toList(); + if (missingKeys.isNotEmpty) { + throw MissingRequiredKeysException(missingKeys, map); + } + } + + if (map != null && disallowNullValues != null) { + final nullValuedKeys = map.entries + .where((entry) => + disallowNullValues.contains(entry.key) && entry.value == null) + .map((entry) => entry.key as String) + .toList(); + + if (nullValuedKeys.isNotEmpty) { + throw DisallowedNullValueException(nullValuedKeys, map); + } + } +} + +/// A base class for exceptions thrown when decoding JSON. +abstract class BadKeyException implements Exception { + BadKeyException._(this.map); + + /// The source [Map] that the unrecognized keys were found in. + final Map map; + + /// A human-readable message corresponding to the error. + String get message; +} + +/// Exception thrown if there are unrecognized keys in a JSON map that was +/// provided during deserialization. +class UnrecognizedKeysException extends BadKeyException { + /// The allowed keys for [map]. + final List allowedKeys; + + /// The keys from [map] that were unrecognized. + final List unrecognizedKeys; + + @override + String get message => + 'Unrecognized keys: [${unrecognizedKeys.join(', ')}]; supported keys: ' + '[${allowedKeys.join(', ')}]'; + + UnrecognizedKeysException(this.unrecognizedKeys, Map map, this.allowedKeys) + : super._(map); + + @override + String toString() => message; +} + +/// Exception thrown if there are missing required keys in a JSON map that was +/// provided during deserialization. +class MissingRequiredKeysException extends BadKeyException { + /// The keys that [map] is missing. + final List missingKeys; + + @override + String get message => 'Required keys are missing: ${missingKeys.join(', ')}.'; + + MissingRequiredKeysException(this.missingKeys, Map map) + : assert(missingKeys.isNotEmpty), + super._(map); +} + +/// Exception thrown if there are keys with disallowed `null` values in a JSON +/// map that was provided during deserialization. +class DisallowedNullValueException extends BadKeyException { + final List keysWithNullValues; + + DisallowedNullValueException(this.keysWithNullValues, Map map) : super._(map); + + @override + String get message => 'These keys had `null` values, ' + 'which is not allowed: $keysWithNullValues'; +} diff --git a/json_annotation-3.1.1/lib/src/checked_helpers.dart b/json_annotation-3.1.1/lib/src/checked_helpers.dart new file mode 100644 index 000000000..f3311a3e9 --- /dev/null +++ b/json_annotation-3.1.1/lib/src/checked_helpers.dart @@ -0,0 +1,131 @@ +// 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. + +import 'allowed_keys_helpers.dart'; + +/// Helper function used in generated code when +/// `JsonSerializableGenerator.checked` is `true`. +/// +/// Should not be used directly. +T $checkedNew(String className, Map map, T Function() constructor, + {Map fieldKeyMap}) { + fieldKeyMap ??= const {}; + + try { + return constructor(); + } on CheckedFromJsonException catch (e) { + if (identical(e.map, map) && e._className == null) { + e._className = className; + } + rethrow; + } catch (error, stack) { + String key; + if (error is ArgumentError) { + key = fieldKeyMap[error.name] ?? error.name; + } else if (error is MissingRequiredKeysException) { + key = error.missingKeys.first; + } else if (error is DisallowedNullValueException) { + key = error.keysWithNullValues.first; + } + throw CheckedFromJsonException._(error, stack, map, key, + className: className); + } +} + +/// Helper function used in generated code when +/// `JsonSerializableGenerator.checked` is `true`. +/// +/// Should not be used directly. +T $checkedConvert(Map map, String key, T Function(Object) castFunc) { + try { + return castFunc(map[key]); + } on CheckedFromJsonException { + rethrow; + } catch (error, stack) { + throw CheckedFromJsonException._(error, stack, map, key); + } +} + +/// Exception thrown if there is a runtime exception in `fromJson` +/// code generated when `JsonSerializableGenerator.checked` is `true` +class CheckedFromJsonException implements Exception { + /// The [Error] or [Exception] that triggered this exception. + /// + /// If this instance was created by user code, this field will be `null`. + final Object innerError; + + /// The [StackTrace] for the [Error] or [Exception] that triggered this + /// exception. + /// + /// If this instance was created by user code, this field will be `null`. + final StackTrace innerStack; + + /// The key from [map] that corresponds to the thrown [innerError]. + /// + /// May be `null`. + final String key; + + /// The source [Map] that was used for decoding when the [innerError] was + /// thrown. + final Map map; + + /// A human-readable message corresponding to [innerError]. + /// + /// May be `null`. + final String message; + + /// The name of the class being created when [innerError] was thrown. + String get className => _className; + String _className; + + /// If this was thrown due to an invalid or unsupported key, as opposed to an + /// invalid value. + final bool badKey; + + /// Creates a new instance of [CheckedFromJsonException]. + CheckedFromJsonException( + this.map, + this.key, + String className, + this.message, { + bool badKey = false, + }) : _className = className, + badKey = badKey ?? false, + innerError = null, + innerStack = null; + + CheckedFromJsonException._( + this.innerError, + this.innerStack, + this.map, + this.key, { + String className, + }) : _className = className, + badKey = innerError is BadKeyException, + message = _getMessage(innerError); + + static String _getMessage(Object error) { + if (error is ArgumentError) { + return error.message?.toString(); + } else if (error is BadKeyException) { + return error.message; + } else if (error is FormatException) { + var message = error.message; + if (error.offset != null) { + message = '$message at offset ${error.offset}.'; + } + return message; + } + return error.toString(); + } + + @override + String toString() => [ + 'CheckedFromJsonException', + if (_className != null) 'Could not create `$_className`.', + if (key != null) 'There is a problem with "$key".', + if (message != null) message, + if (message == null && innerError != null) innerError.toString(), + ].join('\n'); +} diff --git a/json_annotation-3.1.1/lib/src/json_converter.dart b/json_annotation-3.1.1/lib/src/json_converter.dart new file mode 100644 index 000000000..ef1fddf91 --- /dev/null +++ b/json_annotation-3.1.1/lib/src/json_converter.dart @@ -0,0 +1,14 @@ +// 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. + +/// Implement this class to provide custom converters for a specific [Type]. +/// +/// [T] is the data type you'd like to convert to and from. +/// +/// [S] is the type of the value stored in JSON. It must be a valid JSON type +/// such as [String], [int], or [Map]. +abstract class JsonConverter { + T fromJson(S json); + S toJson(T object); +} diff --git a/json_annotation-3.1.1/lib/src/json_key.dart b/json_annotation-3.1.1/lib/src/json_key.dart new file mode 100644 index 000000000..718a87187 --- /dev/null +++ b/json_annotation-3.1.1/lib/src/json_key.dart @@ -0,0 +1,121 @@ +// 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. + +import 'allowed_keys_helpers.dart'; +import 'json_serializable.dart'; + +/// An annotation used to specify how a field is serialized. +class JsonKey { + /// The value to use if the source JSON does not contain this key or if the + /// value is `null`. + final Object defaultValue; + + /// If `true`, generated code will throw a [DisallowedNullValueException] if + /// the corresponding key exists, but the value is `null`. + /// + /// Note: this value does not affect the behavior of a JSON map *without* the + /// associated key. + /// + /// If [disallowNullValue] is `true`, [includeIfNull] will be treated as + /// `false` to ensure compatibility between `toJson` and `fromJson`. + /// + /// If both [includeIfNull] and [disallowNullValue] are set to `true` on the + /// same field, an exception will be thrown during code generation. + final bool disallowNullValue; + + /// A [Function] to use when decoding the associated JSON value to the + /// annotated field. + /// + /// Must be a top-level or static [Function] that takes one argument mapping + /// a JSON literal to a value compatible with the type of the annotated field. + /// + /// When creating a class that supports both `toJson` and `fromJson` + /// (the default), you should also set [toJson] if you set [fromJson]. + /// Values returned by [toJson] should "round-trip" through [fromJson]. + final Function fromJson; + + /// `true` if the generator should ignore this field completely. + /// + /// If `null` (the default) or `false`, the field will be considered for + /// serialization. + final bool ignore; + + /// Whether the generator should include fields with `null` values in the + /// serialized output. + /// + /// If `true`, the generator should include the field in the serialized + /// output, even if the value is `null`. + /// + /// The default value, `null`, indicates that the behavior should be + /// acquired from the [JsonSerializable.includeIfNull] annotation on the + /// enclosing class. + /// + /// If [disallowNullValue] is `true`, this value is treated as `false` to + /// ensure compatibility between `toJson` and `fromJson`. + /// + /// If both [includeIfNull] and [disallowNullValue] are set to `true` on the + /// same field, an exception will be thrown during code generation. + final bool includeIfNull; + + /// The key in a JSON map to use when reading and writing values corresponding + /// to the annotated fields. + /// + /// If `null`, the field name is used. + final String name; + + /// When `true`, `null` fields are handled gracefully when encoding to JSON + /// and when decoding `null` and nonexistent values from JSON. + /// + /// Setting to `false` eliminates `null` verification in the generated code + /// for the annotated field, which reduces the code size. Errors may be thrown + /// at runtime if `null` values are encountered, but the original class should + /// also implement `null` runtime validation if it's critical. + /// + /// The default value, `null`, indicates that the behavior should be + /// acquired from the [JsonSerializable.nullable] annotation on the + /// enclosing class. + final bool nullable; + + /// When `true`, generated code for `fromJson` will verify that the source + /// JSON map contains the associated key. + /// + /// If the key does not exist, a [MissingRequiredKeysException] exception is + /// thrown. + /// + /// Note: only the existence of the key is checked. A key with a `null` value + /// is considered valid. + final bool required; + + /// A [Function] to use when encoding the annotated field to JSON. + /// + /// Must be a top-level or static [Function] with one parameter compatible + /// with the field being serialized that returns a JSON-compatible value. + /// + /// When creating a class that supports both `toJson` and `fromJson` + /// (the default), you should also set [fromJson] if you set [toJson]. + /// Values returned by [toJson] should "round-trip" through [fromJson]. + final Function toJson; + + /// The value to use for an enum field when the value provided is not in the + /// source enum. + /// + /// Valid only on enum fields with a compatible enum value. + final Object unknownEnumValue; + + /// Creates a new [JsonKey] instance. + /// + /// Only required when the default behavior is not desired. + const JsonKey({ + this.defaultValue, + this.disallowNullValue, + this.fromJson, + this.ignore, + this.includeIfNull, + this.name, + this.nullable, + this.required, + this.toJson, + this.unknownEnumValue, + }); +} diff --git a/json_annotation-3.1.1/lib/src/json_literal.dart b/json_annotation-3.1.1/lib/src/json_literal.dart new file mode 100644 index 000000000..06551d62a --- /dev/null +++ b/json_annotation-3.1.1/lib/src/json_literal.dart @@ -0,0 +1,29 @@ +// Copyright (c) 2017, 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. + +/// An annotation used to generate a private field containing the contents of a +/// JSON file. +/// +/// The annotation can be applied to any member, but usually it's applied to +/// top-level getter. +/// +/// In this example, the JSON content of `data.json` is populated into a +/// top-level, final field `_$glossaryDataJsonLiteral` in the generated file. +/// +/// ```dart +/// @JsonLiteral('data.json') +/// Map get glossaryData => _$glossaryDataJsonLiteral; +/// ``` +class JsonLiteral { + /// The relative path from the Dart file with the annotation to the file + /// containing the source JSON. + final String path; + + /// `true` if the JSON literal should be written as a constant. + final bool asConst; + + /// Creates a new [JsonLiteral] instance. + const JsonLiteral(this.path, {bool asConst = false}) + : asConst = asConst ?? false; +} diff --git a/json_annotation-3.1.1/lib/src/json_serializable.dart b/json_annotation-3.1.1/lib/src/json_serializable.dart new file mode 100644 index 000000000..d5ab9d5e7 --- /dev/null +++ b/json_annotation-3.1.1/lib/src/json_serializable.dart @@ -0,0 +1,243 @@ +// Copyright (c) 2017, 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. + +import 'allowed_keys_helpers.dart'; +import 'checked_helpers.dart'; +import 'json_key.dart'; + +part 'json_serializable.g.dart'; + +/// Values for the automatic field renaming behavior for [JsonSerializable]. +enum FieldRename { + /// Use the field name without changes. + none, + + /// Encodes a field named `kebabCase` with a JSON key `kebab-case`. + kebab, + + /// Encodes a field named `snakeCase` with a JSON key `snake_case`. + snake, + + /// Encodes a field named `pascalCase` with a JSON key `PascalCase`. + pascal +} + +/// An annotation used to specify a class to generate code for. +@JsonSerializable( + checked: true, + disallowUnrecognizedKeys: true, + fieldRename: FieldRename.snake, +) +class JsonSerializable { + /// If `true`, [Map] types are *not* assumed to be [Map] + /// – which is the default type of [Map] instances return by JSON decode in + /// `dart:convert`. + /// + /// This will increase the code size, but allows [Map] types returned + /// from other sources, such as `package:yaml`. + /// + /// *Note: in many cases the key values are still assumed to be [String]*. + final bool anyMap; + + /// If `true`, generated `fromJson` functions include extra checks to validate + /// proper deserialization of types. + /// + /// If an exception is thrown during deserialization, a + /// [CheckedFromJsonException] is thrown. + final bool checked; + + /// If `true` (the default), a private, static `_$ExampleFromJson` method + /// is created in the generated part file. + /// + /// Call this method from a factory constructor added to the source class: + /// + /// ```dart + /// @JsonSerializable() + /// class Example { + /// // ... + /// factory Example.fromJson(Map json) => + /// _$ExampleFromJson(json); + /// } + /// ``` + final bool createFactory; + + /// If `true` (the default), A top-level function is created that you can + /// reference from your class. + /// + /// ```dart + /// @JsonSerializable() + /// class Example { + /// Map toJson() => _$ExampleToJson(this); + /// } + /// ``` + final bool createToJson; + + /// If `false` (the default), then the generated `FromJson` function will + /// ignore unrecognized keys in the provided JSON [Map]. + /// + /// If `true`, unrecognized keys will cause an [UnrecognizedKeysException] to + /// be thrown. + final bool disallowUnrecognizedKeys; + + /// If `true`, generated `toJson` methods will explicitly call `toJson` on + /// nested objects. + /// + /// When using JSON encoding support in `dart:convert`, `toJson` is + /// automatically called on objects, so the default behavior + /// (`explicitToJson: false`) is to omit the `toJson` call. + /// + /// Example of `explicitToJson: false` (default) + /// + /// ```dart + /// Map toJson() => {'child': child}; + /// ``` + /// + /// Example of `explicitToJson: true` + /// + /// ```dart + /// Map toJson() => {'child': child?.toJson()}; + /// ``` + final bool explicitToJson; + + /// Defines the automatic naming strategy when converting class field names + /// into JSON map keys. + /// + /// With a value [FieldRename.none] (the default), the name of the field is + /// used without modification. + /// + /// See [FieldRename] for details on the other options. + /// + /// Note: the value for [JsonKey.name] takes precedence over this option for + /// fields annotated with [JsonKey]. + final FieldRename fieldRename; + + /// When `true` on classes with type parameters (generic types), extra + /// "helper" parameters will be generated for `fromJson` and/or `toJson` to + /// support serializing values of those types. + /// + /// For example, the generated code for + /// + /// ```dart + /// @JsonSerializable(genericArgumentFactories: true) + /// class Response { + /// int status; + /// T value; + /// } + /// ``` + /// + /// Looks like + /// + /// ```dart + /// Response _$ResponseFromJson( + /// Map json, + /// T Function(Object json) fromJsonT, + /// ) { + /// return Response() + /// ..status = json['status'] as int + /// ..value = fromJsonT(json['value']); + /// } + /// + /// Map _$ResponseToJson( + /// Response instance, + /// Object Function(T value) toJsonT, + /// ) => + /// { + /// 'status': instance.status, + /// 'value': toJsonT(instance.value), + /// }; + /// ``` + /// + /// Notes: + /// + /// 1. This option has no effect on classes without type parameters. + /// If used on such a class, a warning is echoed in the build log. + /// 1. If this option is set for all classes in a package via `build.yaml` + /// it is only applied to classes with type parameters – so no warning is + /// echoed. + final bool genericArgumentFactories; + + /// When `true`, only fields annotated with [JsonKey] will have code + /// generated. + /// + /// It will have the same effect as if those fields had been annotated with + /// `@JsonKey(ignore: true)`. + final bool ignoreUnannotated; + + /// Whether the generator should include fields with `null` values in the + /// serialized output. + /// + /// If `true` (the default), all fields are written to JSON, even if they are + /// `null`. + /// + /// If a field is annotated with `JsonKey` with a non-`null` value for + /// `includeIfNull`, that value takes precedent. + final bool includeIfNull; + + /// When `true` (the default), `null` fields are handled gracefully when + /// encoding to JSON and when decoding `null` and nonexistent values from + /// JSON. + /// + /// Setting to `false` eliminates `null` verification in the generated code, + /// which reduces the code size. Errors may be thrown at runtime if `null` + /// values are encountered, but the original class should also implement + /// `null` runtime validation if it's critical. + final bool nullable; + + /// Creates a new [JsonSerializable] instance. + const JsonSerializable({ + this.anyMap, + this.checked, + this.createFactory, + this.createToJson, + this.disallowUnrecognizedKeys, + this.explicitToJson, + this.fieldRename, + this.ignoreUnannotated, + this.includeIfNull, + this.nullable, + this.genericArgumentFactories, + }); + + factory JsonSerializable.fromJson(Map json) => + _$JsonSerializableFromJson(json); + + /// An instance of [JsonSerializable] with all fields set to their default + /// values. + static const defaults = JsonSerializable( + anyMap: false, + checked: false, + createFactory: true, + createToJson: true, + disallowUnrecognizedKeys: false, + explicitToJson: false, + fieldRename: FieldRename.none, + ignoreUnannotated: false, + includeIfNull: true, + nullable: true, + genericArgumentFactories: false, + ); + + /// Returns a new [JsonSerializable] instance with fields equal to the + /// corresponding values in `this`, if not `null`. + /// + /// Otherwise, the returned value has the default value as defined in + /// [defaults]. + JsonSerializable withDefaults() => JsonSerializable( + anyMap: anyMap ?? defaults.anyMap, + checked: checked ?? defaults.checked, + createFactory: createFactory ?? defaults.createFactory, + createToJson: createToJson ?? defaults.createToJson, + disallowUnrecognizedKeys: + disallowUnrecognizedKeys ?? defaults.disallowUnrecognizedKeys, + explicitToJson: explicitToJson ?? defaults.explicitToJson, + fieldRename: fieldRename ?? defaults.fieldRename, + ignoreUnannotated: ignoreUnannotated ?? defaults.ignoreUnannotated, + includeIfNull: includeIfNull ?? defaults.includeIfNull, + nullable: nullable ?? defaults.nullable, + genericArgumentFactories: + genericArgumentFactories ?? defaults.genericArgumentFactories, + ); + + Map toJson() => _$JsonSerializableToJson(this); +} diff --git a/json_annotation-3.1.1/lib/src/json_serializable.g.dart b/json_annotation-3.1.1/lib/src/json_serializable.g.dart new file mode 100644 index 000000000..1cf54e387 --- /dev/null +++ b/json_annotation-3.1.1/lib/src/json_serializable.g.dart @@ -0,0 +1,108 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'json_serializable.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +JsonSerializable _$JsonSerializableFromJson(Map json) { + return $checkedNew('JsonSerializable', json, () { + $checkKeys(json, allowedKeys: const [ + 'any_map', + 'checked', + 'create_factory', + 'create_to_json', + 'disallow_unrecognized_keys', + 'explicit_to_json', + 'field_rename', + 'generic_argument_factories', + 'ignore_unannotated', + 'include_if_null', + 'nullable' + ]); + final val = JsonSerializable( + anyMap: $checkedConvert(json, 'any_map', (v) => v as bool), + checked: $checkedConvert(json, 'checked', (v) => v as bool), + createFactory: $checkedConvert(json, 'create_factory', (v) => v as bool), + createToJson: $checkedConvert(json, 'create_to_json', (v) => v as bool), + disallowUnrecognizedKeys: + $checkedConvert(json, 'disallow_unrecognized_keys', (v) => v as bool), + explicitToJson: + $checkedConvert(json, 'explicit_to_json', (v) => v as bool), + fieldRename: $checkedConvert(json, 'field_rename', + (v) => _$enumDecodeNullable(_$FieldRenameEnumMap, v)), + ignoreUnannotated: + $checkedConvert(json, 'ignore_unannotated', (v) => v as bool), + includeIfNull: $checkedConvert(json, 'include_if_null', (v) => v as bool), + nullable: $checkedConvert(json, 'nullable', (v) => v as bool), + genericArgumentFactories: + $checkedConvert(json, 'generic_argument_factories', (v) => v as bool), + ); + return val; + }, fieldKeyMap: const { + 'anyMap': 'any_map', + 'createFactory': 'create_factory', + 'createToJson': 'create_to_json', + 'disallowUnrecognizedKeys': 'disallow_unrecognized_keys', + 'explicitToJson': 'explicit_to_json', + 'fieldRename': 'field_rename', + 'ignoreUnannotated': 'ignore_unannotated', + 'includeIfNull': 'include_if_null', + 'genericArgumentFactories': 'generic_argument_factories' + }); +} + +Map _$JsonSerializableToJson(JsonSerializable instance) => + { + 'any_map': instance.anyMap, + 'checked': instance.checked, + 'create_factory': instance.createFactory, + 'create_to_json': instance.createToJson, + 'disallow_unrecognized_keys': instance.disallowUnrecognizedKeys, + 'explicit_to_json': instance.explicitToJson, + 'field_rename': _$FieldRenameEnumMap[instance.fieldRename], + 'generic_argument_factories': instance.genericArgumentFactories, + 'ignore_unannotated': instance.ignoreUnannotated, + 'include_if_null': instance.includeIfNull, + 'nullable': instance.nullable, + }; + +T _$enumDecode( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} + +T _$enumDecodeNullable( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode(enumValues, source, unknownValue: unknownValue); +} + +const _$FieldRenameEnumMap = { + FieldRename.none: 'none', + FieldRename.kebab: 'kebab', + FieldRename.snake: 'snake', + FieldRename.pascal: 'pascal', +}; diff --git a/json_annotation-3.1.1/lib/src/json_value.dart b/json_annotation-3.1.1/lib/src/json_value.dart new file mode 100644 index 000000000..4e5cb4f2b --- /dev/null +++ b/json_annotation-3.1.1/lib/src/json_value.dart @@ -0,0 +1,13 @@ +// 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. + +/// An annotation used to specify how a enum value is serialized. +class JsonValue { + /// The value to use when serializing and deserializing. + /// + /// Can be a [String] or an [int]. + final dynamic value; + + const JsonValue(this.value); +} diff --git a/json_annotation-3.1.1/mono_pkg.yaml b/json_annotation-3.1.1/mono_pkg.yaml new file mode 100644 index 000000000..1da53eb18 --- /dev/null +++ b/json_annotation-3.1.1/mono_pkg.yaml @@ -0,0 +1,10 @@ +# See https://github.com/google/mono_repo.dart for details on this file +stages: +- analyzer_and_format: + - group: + - dartfmt + - dartanalyzer: --fatal-warnings --fatal-infos . + dart: [dev] + - group: + - dartanalyzer: --fatal-warnings . + dart: [2.7.0] diff --git a/json_annotation-3.1.1/pubspec.yaml b/json_annotation-3.1.1/pubspec.yaml new file mode 100644 index 000000000..b38331019 --- /dev/null +++ b/json_annotation-3.1.1/pubspec.yaml @@ -0,0 +1,13 @@ +name: json_annotation_3_1_1 +version: 3.1.1 +description: >- + Classes and helper functions that support JSON code generation via the + `json_serializable` package. +homepage: https://github.com/google/json_serializable.dart +environment: + sdk: '>=2.7.0 <3.0.0' + +# When changing JsonSerializable class. +# dev_dependencies: +# build_runner: ^1.0.0 +# json_serializable: ^3.1.0 diff --git a/json_serializable-3.5.2/CHANGELOG.md b/json_serializable-3.5.2/CHANGELOG.md new file mode 100644 index 000000000..bc968298e --- /dev/null +++ b/json_serializable-3.5.2/CHANGELOG.md @@ -0,0 +1,627 @@ +## 3.5.2 + +- Widen `package:analyzer` range to allow v1.x. + +## 3.5.1 + +- Improved error messages for unsupported types. +- `package:json_serializable/type_helper.dart` + - Made the third parameter to `UnsupportedTypeError` positional (optional). +- Require `package:analyzer` `>=0.39.0 <0.42.0`. + +## 3.5.0 + +- Added support for populating generic helper functions for fields with generic + type parameters. +- Added support for `JsonSerializable.genericArgumentFactories`. + This adds extra parameters to generated `fromJson` and/or `toJson` functions + to support encoding and decoding generic types. + + For example, the generated code for + + ```dart + @JsonSerializable(genericArgumentFactories: true) + class Response { + int status; + T value; + } + ``` + + Looks like + + ```dart + Response _$ResponseFromJson( + Map json, + T Function(Object json) fromJsonT, + ) { + return Response() + ..status = json['status'] as int + ..value = fromJsonT(json['value']); + } + + Map _$ResponseToJson( + Response instance, + Object Function(T value) toJsonT, + ) => + { + 'status': instance.status, + 'value': toJsonT(instance.value), + }; + ``` + +- `JsonKey.unknownEnumValue`: Added support for `Iterable`, `List`, and `Set`. +- Require `package:analyzer` `>=0.39.0 <0.41.0`. + +## 3.4.1 + +- Support properties where the getter is defined in a class with a corresponding + setter in a super type. + +## 3.4.0 + +- `JsonKey.defaultValue` + - Added support for `double.infinity`, `double.negativeInfinity`, and + `double.nan`. + - Added support for `Set` literals. +- Require at least Dart `2.7.0`. + +## 3.3.0 + +- Add support for fields annotated subclasses of `JsonKey`. +- Export the following `TypeHelper` implementations and interfaces in + `package:json_serializable/type_helper.dart`: + - `DurationHelper` + - `TypeHelperContextWithConfig` + +## 3.2.5 + +- Fix lint affecting `pub.dev` score. + +## 3.2.4 + +* Require `package:analyzer` `^0.39.0`. + +## 3.2.3 + +* Bug fix for analyzer 0.38.5. + +## 3.2.2 + +* Support `JsonConverter` annotations on property getters + +## 3.2.1 + +* Support `package:analyzer` `>=0.33.3 <0.39.0` + +## 3.2.0 + +- Require `package:json_annotation` `^3.0.0`. +- Added support for `JsonSerializable.ignoreUnannotated`. +- Added support for `JsonKey.unknownEnumValue`. +- Small change to how `enum` support code is generated. +- Require at least Dart `2.3.0`. + +## 3.1.0 + +- Support `Map` keys of type `int`, `BigInt`, `DateTime`, and `Uri`. +- Trailing commas are now added to generated constructor arguments and the + elements in `Map` literals. +- Support `package:analyzer` `>=0.33.3 <0.38.0` + +## 3.0.0 + +This release is entirely **BREAKING** changes. It removes underused features +that added disproportionate complexity to this package. This cleanup should ease +future feature work. + +- Removed support for `JsonSerializable.useWrappers`. +- Removed support for `JsonSerializable.generateToJsonFunction`. +- Removed support for `encodeEmptyCollection`. +- If a field has a conversion function defined – either + `JsonKey.toJson` or a custom `JsonConverter` annotation – don't intercept + `null` values, even if `nullable` is explicitly set to `false`. This allows + these functions to provide alternative values for `null` – such as an empty + collection – which replaces the functionality provided by + `encodeEmptyCollection`. + - **NOTE: this is SILENTLY BREAKING.** There is no corresponding deprecation + for this change. If you use converters, please make sure to test your + code! + +## 2.3.0 + +- Added `pascal` as an additional `fieldRename` option. + +## 2.2.3 + +- Removed special handling of undefined types due to changes in + `package:analyzer`. These types are now treated as `dynamic`. + +## 2.2.2 + +- Require at least Dart `2.2.0`. +- Allow `build_config` `0.4.x`. + +## 2.2.1 + +- Fixed an error when a property/field is defined in a `mixin`. + +## 2.2.0 + +- If a field has a conversion function defined – either `JsonKey.toJson` or a + custom `JsonConverter` annotation – handle the case where the function + returns `null` and both `nullable` and `includeIfNull` are `false`. + +## 2.1.2 + +* Support `package:json_annotation` `>=2.1.0 <2.3.0`. + +## 2.1.1 + +* Support `package:analyzer` `>=0.33.3 <0.37.0` + +## 2.1.0 + +* Require at least Dart `2.1.1`. + +* Added support for `encodeEmptyCollection` on `JsonKey` and `JsonSerializable`. + +* Added support for `BigInt`. + +* Added `BigIntTypeHelper` to `type_helper.dart` library. + +* Provide a more helpful error if the builder is improperly configured. + +## 2.0.3 + +* When invoking a `fromJson` constructor on a field type, generate a conversion + expression derived from the the constructor parameter type. + +* Be more strict about the supported `List`, `Set`, or `Map` types. + This may causes errors to be raised in cases where invalid code was generated + before. It also allows implementations of these types to add a `fromJson` + constructor to support custom decoding. + +* Small change to the whitespace around converted maps to improve a very slow + path when formatting generated code. + +## 2.0.2 + +* Log warnings when `JsonKey.defaultValue` is set with other fields. + * With `toJson`: use `nullable: false` instead of `defaultValue`. + * With both `disallowNullValue` and `required` set to `true`. + +* Avoid no-op call to `map` when decoding a field of type `Set`. + +* Support `package:analyzer` `>=0.33.3 <0.36.0` + +## 2.0.1 + +* Support `package:analyzer` v0.34.0. + +## 2.0.0 + +* Support all `build.yaml` configuration options on classes by adding a number + of fields to `JsonSerializable`: `anyMap`, `checked`, `explicitToJson`, + `generateToJsonFunction`, and `useWrappers`. + +* Support decode/encode of `dart:core` `Duration` + +* Code generated for fields and classes annotated with `JsonConverter` instances + now properly handles nullable fields. + +* Build configuration + + * You can now configure all settings exposed by the `JsonSerializable` + annotation within `build.yaml`. + + * **BREAKING** Unsupported options defined in `build.yaml` will cause + exceptions instead of being logged and ignored. + +* `json_serializable.dart` + + * **BREAKING** `JsonSerializableGenerator` now exposes a `config` property + of type `JsonSerializable` instead of individual properties for `checked`, + `anyMay`, etc. This will affect anyone creating or using this class via + code. + +* `type_helper.dart` + + * **BREAKING** `SerializeContext` and `DeserializeContext` have been replaced + with new `TypeHelperContext` class. + + * `TypeHelper` now has a type argument allowing implementors to specify a + specific implementation of `TypeHelperContext` for calls to `serialize` and + `deserialize`. Many of the included `TypeHelper` implementations have been + updated to indicate they expect more information from the source generator. + +## 1.5.1 + +* Support the latest `package:analyzer`. + +## 1.5.0 + +* Added support for `JsonConvert` annotation on fields. + +## 1.4.0 + +* `type_helper.dart` + + * `TypeHelper` `serialize` and `deserialize` have return type `Object` instead + of `String`. This allows coordination between instances to support more + advanced features – like using the new `LambdaResult` class to avoid + creating unnecessary lambdas. When creating `TypeHelper` implementations, + handle non-`String` results by calling `toString()` on unrecognized values. + +* Declare support for `package:build` version `1.x.x`. + +## 1.3.0 + +* Add support for types annotated with classes that extend `JsonConverter` from + `package:json_annotation`. + +* Export the following `TypeHelper` implementations in + `package:json_serializable/type_helper.dart`: + `ConvertHelper`, `EnumHelper`, `IterableHelper`, `JsonConverterHelper`, + `MapHelper`, `ValueHelper` + +* Added support for `Set` type as a target. + +## 1.2.1 + +* Added back `const` for maps generated with `checked: true` configuration. + +## 1.2.0 + +* Now throws `InvalidGenerationSourceError` instead of `UnsupportedError` for + some classes of constructor errors. + +* Supports class-static functions for `toJson` and `fromJson` on `JsonKey`. + +* Provide a warning about ignored setter-only properties instead of crashing. + +* Added back `const` for lists generated with `disallowUnrecognizedKeys`, + `required`, and `disallowNullValue`. + +* Fixed a bug when `disallowUnrecognizedKeys` is enabled. + +* Fixed a number of issues when dealing with inherited properties. + +## 1.1.0 + +* Added support for automatically converting field names to JSON map keys as + `kebab-case` or `snake_case` with a new option on the `JsonSerializable` + annotation. + +## 1.0.1 + +* Explicit `new` and `const` are no longer generated. + +## 1.0.0 + +* **BREAKING** By default, code generated to support `toJson` now creates + a top-level function instead of a mixin. The default for the + `generate_to_json_function` is now `true`. To opt-out of this change, + set `generate_to_json_function` to `false`. + +* Now supports changing the serialized values of enums using `JsonValue`. + + ```dart + enum AutoApply { + none, + dependents, + @JsonValue('all_packages') + allPackages, + @JsonValue('root_package') + rootPackage + } + ``` + +* `JsonSerializableGenerator.generateForAnnotatedElement` now returns + `Iterable` instead of `String`. + +* `SerializeContext` and `DeserializeContext` now have an `addMember` function + which allows `TypeHelper` instances to add additional members when handling + a field. This is useful for generating shared helpers, for instance. + +* **BREAKING** The `header` option is no longer supported and must be removed + from `build.yaml`. + +* If a manual build script is used the `json_serializable` builder must be + switched to `hideOutput: true`, and the `combiningBuilder` from `source_gen` + must be included following this builder. When using a generated build script + with `pub run build_runner` or `webdev` this is handled automatically. + +## 0.5.8+1 + +* Support the Dart 2.0 stable release. + +## 0.5.8 + +* Small fixes to support Dart 2 runtime semantics. + +* Support serializing types provided by platform-specific libraries (such as + Flutter) if they use custom convert functions. + +## 0.5.7 + +* Added support for `JsonKey.required`. + * When `true`, generated code throws a `MissingRequiredKeysException` if + the key does not exist in the JSON map used to populate the annotated field. + * Will be captured and wrapped in a `CheckedFromJsonException` if + `checked` is enabled in `json_serializable`. + +* Added `JsonKey.disallowNullValue`. + * When `true`, generated code throws a `DisallowedNullValueException` if + the corresponding keys exist in in the JSON map, but it's value is null. + * Will be captured and wrapped in a `CheckedFromJsonException` if + `checked` is enabled in `json_serializable`. + +* Added support for `Uri` conversion. + +* Added missing `checked` parameter to the + `JsonSerializableGenerator.withDefaultHelpers` constructor. + +* Added `explicit_to_json` configuration option. + * See `JsonSerializableGenerator.explicitToJson` for details. + +* Added `generate_to_json_function` configuration option. + * See `JsonSerializableGenerator.generateToJsonFunction` for details. + +## 0.5.6 + +* Added support for `JsonSerializable.disallowUnrecognizedKeys`. + * Throws an `UnrecognizedKeysException` if it finds unrecognized keys in the + JSON map used to populate the annotated field. + * Will be 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`. + +* `enum` deserialization now uses helpers provided by `json_annotation`. + +* Small change to how nullable `Map` values are deserialized. + +* Small whitespace changes to `JsonLiteral` generation to align with `dartfmt`. + +* Improve detection of `toJson` and `fromJson` in nested types. + +## 0.5.4+1 + +* Fixed a bug introduced in `0.5.4` in some cases where enum values are nested + in collections. + +## 0.5.4 + +* Add `checked` configuration option. If `true`, generated `fromJson` functions + include extra checks to validate proper deserialization of types. + +* Added `any_map` to configuration. Allows `fromJson` code to + support dynamic `Map` instances that are not explicitly + `Map`. + +* Added support for classes with type arguments. + +* Use `Map.map` for more map conversions. Simplifies generated code and fixes + a subtle issue when the `Map` key type is `dynamic` or `Object`. + +## 0.5.3 + +* Require the latest version of `package:analyzer` - `v0.32.0`. + +* If `JsonKey.fromJson` function parameter is `Iterable` or `Map` with type + arguments of `dynamic` or `Object`, omit the arguments when generating a + cast. + `_myHelper(json['key'] as Map)` instead of + `_myHelper(json['key'] as Map)`. + +* `JsonKey.fromJson`/`.toJson` now support functions with optional arguments. + +## 0.5.2 + +* If `JsonKey.fromJson`/`toJson` are set, apply them before any custom + or default `TypeHelper` instances. This allows custom `DateTime` parsing, + by preempting the existing `DateTime` `TypeHelper`. + +## 0.5.1 + +* Support new `fromJson` and `toJson` fields on `JsonKey`. + +* Use `log` exposed by `package:build`. This requires end-users to have at least + `package:build_runner` `^0.8.2`. + +* Updated minimum `package:source_gen` dependency to `0.8.1` which includes + improved error messages. + +## 0.5.0 + +* **BREAKING** Removed deprecated support for `require_library_directive` / + `requireLibraryDirective` in `build_runner` configuration. + +* **BREAKING** Removed the deprecated `generators.dart` library. + +* **BREAKING** Removed `jsonPartBuilder` function from public API. + +* Support the latest `package:source_gen`. + +* Private and ignored fields are now excluded when generating serialization and + deserialization code by using `@JsonKey(ignore: true)`. + +* Throw an exception if a private field or an ignored field is referenced by a + required constructor argument. + +* More comprehensive escaping of string literals. + +### `package:json_serializable/type_helper.dart` + +* **Breaking** The `nullable` parameter on `TypeHelper.serialize` and + `.deserialize` has been removed. It is now exposed in `SerializeContext` and + `DeserializeContext` abstract classes as a read-only property. + +* **Potentially Breaking** The `metadata` property on `SerializeContext` and + `DeserializeContext` is now readonly. This would potentially break code that + extends these classes – which is not expected. + +## 0.4.0 + +* **Potentially Breaking** Inherited fields are now processed and used + when generating serialization and deserialization code. There is a possibility + that the generated code may change in undesired ways for classes annotated for + `v0.3`. + +* Avoid unnecessary braces in string escapes. + +* Use single quotes when generating code. + +## 0.3.2 + +* The `require_library_directive` option now defaults to `false`. + The option will be removed entirely in `0.4.0`. + +## 0.3.1+2 + +* Support the latest version of the `analyzer` package. + +## 0.3.1+1 + +* Expanded `package:build` support to allow version `0.12.0`. + +## 0.3.1 + +* Add a `build.yaml` so the builder can be consumed by users of `build_runner` + version 0.7.0. + +* Now requires a Dart `2.0.0-dev` release. + +## 0.3.0 + +* **NEW** top-level library `json_serializable.dart`. + + * Replaces now deprecated `generators.dart` to access + `JsonSerializableGenerator` and `JsonLiteralGenerator`. + + * Adds the `jsonPartBuilder` function to make it easy to create a + `PartBuilder`, without creating an explicit dependency on `source_gen`. + +* **BREAKING** `UnsupportedTypeError` added a new required constructor argument: + `reason`. + +* **BREAKING** The deprecated `annotations.dart` library has been removed. + Use `package:json_annotation` instead. + +* **BREAKING** The arguments to `TypeHelper` `serialize` and `deserialize` have + changed. + * `SerializeContext` and `DeserializeContext` (new classes) are now passed + instead of the `TypeHelperGenerator` typedef (which has been deleted). + +* `JsonSerializableGenerator` now supports an optional `useWrappers` argument + when generates and uses wrapper classes to (hopefully) improve the speed and + memory usage of serialization – at the cost of more code. + + **NOTE**: `useWrappers` is not guaranteed to improve the performance of + serialization. Benchmarking is recommended. + +* Make `null` field handling smarter. If a field is classified as not + `nullable`, then use this knowledge when generating serialization code – even + if `includeIfNull` is `false`. + +## 0.2.5 + +* Throw an exception if a duplicate JSON key is detected. + +* Support the `nullable` field on the `JsonSerializable` class annotation. + +## 0.2.4+1 + +* Throw a more helpful error when a constructor is missing. + +## 0.2.4 + +* Moved the annotations in `annotations.dart` to `package:json_annotations`. + * Allows package authors to release code that has the corresponding + annotations without requiring package users to inherit all of the transitive + dependencies. + +* Deprecated `annotations.dart`. + +## 0.2.3 + +* Write out `toJson` methods more efficiently when the first fields written are + not intercepted by the null-checking method. + +## 0.2.2+1 + +* Simplify the serialization of `Map` instances when no conversion is required + for `values`. + +* Handle `int` literals in JSON being assigned to `double` fields. + +## 0.2.2 + +* Enable support for `enum` values. +* Added `asConst` to `JsonLiteral`. +* Improved the handling of Dart-specific characters in JSON strings. + +## 0.2.1 + +* Upgrade to `package:source_gen` v0.7.0 + +## 0.2.0+1 + +* When serializing classes that implement their own `fromJson` constructor, + honor their constructor parameter type. + +## 0.2.0 + +* **BREAKING** Types are now segmented into their own libraries. + + * `package:json_serializable/generators.dart` contains `Generator` + implementations. + + * `package:json_serializable/annotations.dart` contains annotations. + This library should be imported with your target classes. + + * `package:json_serializable/type_helpers.dart` contains `TypeHelper` classes + and related helpers which allow custom generation for specific types. + +* **BREAKING** Generation fails for types that are not a JSON primitive or that + do not explicitly supports JSON serialization. + +* **BREAKING** `TypeHelper`: + + * Removed `can` methods. Return `null` from `(de)serialize` if the provided + type is not supported. + + * Added `(de)serializeNested` arguments to `(de)serialize` methods allowing + generic types. This is how support for `Iterable`, `List`, and `Map` + is implemented. + +* **BREAKING** `JsonKey.jsonName` was renamed to `name` and is now a named + parameter. + +* Added support for optional, non-nullable fields. + +* Added support for excluding `null` values when generating JSON. + +* Eliminated all implicit casts in generated code. These would end up being + runtime checks in most cases. + +* Provide a helpful error when generation fails due to undefined types. + +## 0.1.0+1 + +* Fix homepage in `pubspec.yaml`. + +## 0.1.0 + +* Split off from [source_gen](https://pub.dev/packages/source_gen). + +* Add `/* unsafe */` comments to generated output likely to be unsafe. + +* Support (de)serializing values in `Map`. + +* Fix ordering of fields when they are initialized via constructor. + +* Don't use static members when calculating fields to (de)serialize. diff --git a/json_serializable-3.5.2/LICENSE b/json_serializable-3.5.2/LICENSE new file mode 100644 index 000000000..389ce9856 --- /dev/null +++ b/json_serializable-3.5.2/LICENSE @@ -0,0 +1,26 @@ +Copyright 2017, the Dart project authors. All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/json_serializable-3.5.2/README.md b/json_serializable-3.5.2/README.md new file mode 100644 index 000000000..ef399eb9a --- /dev/null +++ b/json_serializable-3.5.2/README.md @@ -0,0 +1,160 @@ +[![Pub Package](https://img.shields.io/pub/v/json_serializable.svg)](https://pub.dev/packages/json_serializable) + +Provides [Dart Build System] builders for handling JSON. + +The builders generate code when they find members annotated with classes defined +in [package:json_annotation]. + +- To generate to/from JSON code for a class, annotate it with + `@JsonSerializable`. You can provide arguments to `JsonSerializable` to + configure the generated code. You can also customize individual fields + by annotating them with `@JsonKey` and providing custom arguments. + See the table below for details on the + [annotation values](#annotation-values). + +- To generate a Dart field with the contents of a file containing JSON, use the + `JsonLiteral` annotation. + +## Setup + +To configure your project for the latest released version of, +`json_serializable` see the [example]. + +## Example + +Given a library `example.dart` with an `Person` class annotated with +`@JsonSerializable()`: + +```dart +import 'package:json_annotation/json_annotation.dart'; + +part 'example.g.dart'; + +@JsonSerializable(nullable: false) +class Person { + final String firstName; + final String lastName; + final DateTime dateOfBirth; + Person({this.firstName, this.lastName, this.dateOfBirth}); + factory Person.fromJson(Map json) => _$PersonFromJson(json); + Map toJson() => _$PersonToJson(this); +} +``` + +Building creates the corresponding part `example.g.dart`: + +```dart +part of 'example.dart'; + +Person _$PersonFromJson(Map json) { + return Person( + firstName: json['firstName'] as String, + lastName: json['lastName'] as String, + dateOfBirth: DateTime.parse(json['dateOfBirth'] as String), + ); +} + +Map _$PersonToJson(Person instance) => { + 'firstName': instance.firstName, + 'lastName': instance.lastName, + 'dateOfBirth': instance.dateOfBirth.toIso8601String(), + }; +``` + +# Annotation values + +The only annotation required to use this package is `@JsonSerializable`. When +applied to a class (in a correctly configured package), `toJson` and `fromJson` +code will be generated when you build. There are three ways to control how code +is generated: + +1. Set properties on `@JsonSerializable`. +2. Add a `@JsonKey` annotation to a field and set properties there. +3. Add configuration to `build.yaml` – [see below](#build-configuration). + +| `build.yaml` key | JsonSerializable | JsonKey | +| -------------------------- | ------------------------------------------- | --------------------------- | +| any_map | [JsonSerializable.anyMap] | | +| checked | [JsonSerializable.checked] | | +| create_factory | [JsonSerializable.createFactory] | | +| create_to_json | [JsonSerializable.createToJson] | | +| disallow_unrecognized_keys | [JsonSerializable.disallowUnrecognizedKeys] | | +| explicit_to_json | [JsonSerializable.explicitToJson] | | +| field_rename | [JsonSerializable.fieldRename] | | +| generic_argument_factories | [JsonSerializable.genericArgumentFactories] | | +| ignore_unannotated | [JsonSerializable.ignoreUnannotated] | | +| include_if_null | [JsonSerializable.includeIfNull] | [JsonKey.includeIfNull] | +| nullable | [JsonSerializable.nullable] | [JsonKey.nullable] | +| | | [JsonKey.defaultValue] | +| | | [JsonKey.disallowNullValue] | +| | | [JsonKey.fromJson] | +| | | [JsonKey.ignore] | +| | | [JsonKey.name] | +| | | [JsonKey.required] | +| | | [JsonKey.toJson] | +| | | [JsonKey.unknownEnumValue] | + +[JsonSerializable.anyMap]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/anyMap.html +[JsonSerializable.checked]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/checked.html +[JsonSerializable.createFactory]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/createFactory.html +[JsonSerializable.createToJson]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/createToJson.html +[JsonSerializable.disallowUnrecognizedKeys]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/disallowUnrecognizedKeys.html +[JsonSerializable.explicitToJson]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/explicitToJson.html +[JsonSerializable.fieldRename]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/fieldRename.html +[JsonSerializable.genericArgumentFactories]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/genericArgumentFactories.html +[JsonSerializable.ignoreUnannotated]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/ignoreUnannotated.html +[JsonSerializable.includeIfNull]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/includeIfNull.html +[JsonKey.includeIfNull]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/includeIfNull.html +[JsonSerializable.nullable]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/nullable.html +[JsonKey.nullable]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/nullable.html +[JsonKey.defaultValue]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/defaultValue.html +[JsonKey.disallowNullValue]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/disallowNullValue.html +[JsonKey.fromJson]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/fromJson.html +[JsonKey.ignore]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/ignore.html +[JsonKey.name]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/name.html +[JsonKey.required]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/required.html +[JsonKey.toJson]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/toJson.html +[JsonKey.unknownEnumValue]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/unknownEnumValue.html + +> Note: every `JsonSerializable` field is configurable via `build.yaml` – + see the table for the corresponding key. + If you find you want all or most of your classes with the same configuration, + it may be easier to specify values once in the YAML file. Values set + explicitly on `@JsonSerializable` take precedence over settings in + `build.yaml`. + +> Note: There is some overlap between fields on `JsonKey` and + `JsonSerializable`. In these cases, if a value is set explicitly via `JsonKey` + it will take precedence over any value set on `JsonSerializable`. + +# Build configuration + +Besides setting arguments on the associated annotation classes, you can also +configure code generation by setting values in `build.yaml`. + +```yaml +targets: + $default: + builders: + json_serializable: + options: + # Options configure how source code is generated for every + # `@JsonSerializable`-annotated class in the package. + # + # The default value for each is listed. + any_map: false + checked: false + create_factory: true + create_to_json: true + disallow_unrecognized_keys: false + explicit_to_json: false + field_rename: none + generic_argument_factories: false + ignore_unannotated: false + include_if_null: true + nullable: true +``` + +[example]: https://github.com/google/json_serializable.dart/tree/master/example +[Dart Build System]: https://github.com/dart-lang/build +[package:json_annotation]: https://pub.dev/packages/json_annotation diff --git a/json_serializable-3.5.2/build.yaml b/json_serializable-3.5.2/build.yaml new file mode 100644 index 000000000..ac2d9172d --- /dev/null +++ b/json_serializable-3.5.2/build.yaml @@ -0,0 +1,115 @@ +# Read about `build.yaml` at https://pub.dev/packages/build_config +targets: + $default: + builders: + json_serializable: + generate_for: + - example/* + - test/default_value/* + - test/generic_files/* + - test/integration/* + - test/kitchen_sink/* + - test/literal/* + - test/supported_types/* + + build_web_compilers|entrypoint: + generate_for: + - test/**/**.browser_test.dart + + json_serializable|_test_builder: + generate_for: + - test/default_value/default_value.dart + - test/generic_files/generic_class.dart + - test/integration/json_test_example.dart + - test/integration/json_test_example.dart + - test/integration/json_test_example.non_nullable.dart + - test/kitchen_sink/kitchen_sink.dart + + json_serializable|_type_builder: + generate_for: + - test/supported_types/input.dart + + json_serializable|_type_test_builder: + generate_for: + - test/supported_types/type_test.dart + +builders: + _test_builder: + import: 'tool/test_builder.dart' + builder_factories: ['testBuilder'] + build_extensions: + .dart: + - .factories.dart + - .g_any_map.dart + - .g_any_map__checked.dart + - .g_any_map__checked__non_nullable.dart + - .g_any_map__non_nullable.dart + - .g_exclude_null.dart + - .g_exclude_null__non_nullable.dart + - .g_explicit_to_json.dart + - .g_non_nullable.dart + build_to: source + runs_before: ["json_serializable"] + + _type_builder: + import: 'tool/test_type_builder.dart' + builder_factories: ['typeBuilder'] + build_extensions: + .dart: + - .type_bigint.dart + - .type_bool.dart + - .type_datetime.dart + - .type_double.dart + - .type_duration.dart + - .type_enumtype.dart + - .type_int.dart + - .type_iterable.dart + - .type_list.dart + - .type_map.dart + - .type_num.dart + - .type_object.dart + - .type_set.dart + - .type_string.dart + - .type_uri.dart + build_to: source + runs_before: ["json_serializable"] + + _type_test_builder: + import: 'tool/test_type_builder.dart' + builder_factories: ['typeTestBuilder'] + build_extensions: + .dart: + - .bigint_test.dart + - .bool_test.dart + - .datetime_test.dart + - .double_test.dart + - .duration_test.dart + - .enumtype_test.dart + - .int_test.dart + - .iterable_test.dart + - .list_test.dart + - .map_test.dart + - .num_test.dart + - .object_test.dart + - .set_test.dart + - .string_test.dart + - .uri_test.dart + build_to: source + runs_before: ["json_serializable"] + + _doc_builder: + import: "tool/doc_builder.dart" + builder_factories: ["docBuilder"] + build_extensions: {"lib/json_serializable.dart": ["doc/doc.md"]} + build_to: source + auto_apply: root_package + runs_before: ["json_serializable"] + required_inputs: ["doc/json_annotation_version.txt"] + + json_serializable: + import: "package:json_serializable/builder.dart" + builder_factories: ["jsonSerializable"] + build_extensions: {".dart": ["json_serializable.g.part"]} + auto_apply: dependents + build_to: cache + applies_builders: ["source_gen|combining_builder"] diff --git a/json_serializable-3.5.2/dart_test.yaml b/json_serializable-3.5.2/dart_test.yaml new file mode 100644 index 000000000..1d7ac69cc --- /dev/null +++ b/json_serializable-3.5.2/dart_test.yaml @@ -0,0 +1,3 @@ +tags: + presubmit-only: + skip: "Should only be run during presubmit" diff --git a/json_serializable-3.5.2/doc/doc.md b/json_serializable-3.5.2/doc/doc.md new file mode 100644 index 000000000..76c6c2d7d --- /dev/null +++ b/json_serializable-3.5.2/doc/doc.md @@ -0,0 +1,43 @@ +| `build.yaml` key | JsonSerializable | JsonKey | +| -------------------------- | ------------------------------------------- | --------------------------- | +| any_map | [JsonSerializable.anyMap] | | +| checked | [JsonSerializable.checked] | | +| create_factory | [JsonSerializable.createFactory] | | +| create_to_json | [JsonSerializable.createToJson] | | +| disallow_unrecognized_keys | [JsonSerializable.disallowUnrecognizedKeys] | | +| explicit_to_json | [JsonSerializable.explicitToJson] | | +| field_rename | [JsonSerializable.fieldRename] | | +| generic_argument_factories | [JsonSerializable.genericArgumentFactories] | | +| ignore_unannotated | [JsonSerializable.ignoreUnannotated] | | +| include_if_null | [JsonSerializable.includeIfNull] | [JsonKey.includeIfNull] | +| nullable | [JsonSerializable.nullable] | [JsonKey.nullable] | +| | | [JsonKey.defaultValue] | +| | | [JsonKey.disallowNullValue] | +| | | [JsonKey.fromJson] | +| | | [JsonKey.ignore] | +| | | [JsonKey.name] | +| | | [JsonKey.required] | +| | | [JsonKey.toJson] | +| | | [JsonKey.unknownEnumValue] | + +[JsonSerializable.anyMap]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/anyMap.html +[JsonSerializable.checked]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/checked.html +[JsonSerializable.createFactory]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/createFactory.html +[JsonSerializable.createToJson]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/createToJson.html +[JsonSerializable.disallowUnrecognizedKeys]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/disallowUnrecognizedKeys.html +[JsonSerializable.explicitToJson]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/explicitToJson.html +[JsonSerializable.fieldRename]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/fieldRename.html +[JsonSerializable.genericArgumentFactories]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/genericArgumentFactories.html +[JsonSerializable.ignoreUnannotated]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/ignoreUnannotated.html +[JsonSerializable.includeIfNull]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/includeIfNull.html +[JsonKey.includeIfNull]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/includeIfNull.html +[JsonSerializable.nullable]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonSerializable/nullable.html +[JsonKey.nullable]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/nullable.html +[JsonKey.defaultValue]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/defaultValue.html +[JsonKey.disallowNullValue]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/disallowNullValue.html +[JsonKey.fromJson]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/fromJson.html +[JsonKey.ignore]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/ignore.html +[JsonKey.name]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/name.html +[JsonKey.required]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/required.html +[JsonKey.toJson]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/toJson.html +[JsonKey.unknownEnumValue]: https://pub.dev/documentation/json_annotation/3.1.0/json_annotation/JsonKey/unknownEnumValue.html diff --git a/json_serializable-3.5.2/example/example.dart b/json_serializable-3.5.2/example/example.dart new file mode 100644 index 000000000..b62fd38f1 --- /dev/null +++ b/json_serializable-3.5.2/example/example.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2017, 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'example.g.dart'; + +@JsonSerializable(nullable: false) +class Person { + final String firstName; + final String lastName; + final DateTime dateOfBirth; + Person({this.firstName, this.lastName, this.dateOfBirth}); + factory Person.fromJson(Map json) => _$PersonFromJson(json); + Map toJson() => _$PersonToJson(this); +} diff --git a/json_serializable-3.5.2/example/example.g.dart b/json_serializable-3.5.2/example/example.g.dart new file mode 100644 index 000000000..4d790cf8c --- /dev/null +++ b/json_serializable-3.5.2/example/example.g.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'example.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +Person _$PersonFromJson(Map json) { + return Person( + firstName: json['firstName'] as String, + lastName: json['lastName'] as String, + dateOfBirth: DateTime.parse(json['dateOfBirth'] as String), + ); +} + +Map _$PersonToJson(Person instance) => { + 'firstName': instance.firstName, + 'lastName': instance.lastName, + 'dateOfBirth': instance.dateOfBirth.toIso8601String(), + }; diff --git a/json_serializable-3.5.2/lib/builder.dart b/json_serializable-3.5.2/lib/builder.dart new file mode 100644 index 000000000..cd9014e26 --- /dev/null +++ b/json_serializable-3.5.2/lib/builder.dart @@ -0,0 +1,44 @@ +// Copyright (c) 2017, 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. + +/// Configuration for using `package:build`-compatible build systems. +/// +/// See: +/// * [build_runner](https://pub.dev/packages/build_runner) +/// +/// This library is **not** intended to be imported by typical end-users unless +/// you are creating a custom compilation pipeline. See documentation for +/// details, and `build.yaml` for how these builders are configured by default. +library json_serializable.builder; + +import 'package:build/build.dart'; +import 'package:json_annotation/json_annotation.dart'; + +import 'src/json_part_builder.dart'; + +/// Supports `package:build_runner` creation and configuration of +/// `json_serializable`. +/// +/// Not meant to be invoked by hand-authored code. +Builder jsonSerializable(BuilderOptions options) { + try { + final config = JsonSerializable.fromJson(options.config); + return jsonPartBuilder(config: config); + } on CheckedFromJsonException catch (e) { + final lines = [ + 'Could not parse the options provided for `json_serializable`.' + ]; + + if (e.key != null) { + lines.add('There is a problem with "${e.key}".'); + } + if (e.message != null) { + lines.add(e.message); + } else if (e.innerError != null) { + lines.add(e.innerError.toString()); + } + + throw StateError(lines.join('\n')); + } +} diff --git a/json_serializable-3.5.2/lib/json_serializable.dart b/json_serializable-3.5.2/lib/json_serializable.dart new file mode 100644 index 000000000..094597df6 --- /dev/null +++ b/json_serializable-3.5.2/lib/json_serializable.dart @@ -0,0 +1,6 @@ +// Copyright (c) 2017, 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. + +export 'src/json_literal_generator.dart' show JsonLiteralGenerator; +export 'src/json_serializable_generator.dart' show JsonSerializableGenerator; diff --git a/json_serializable-3.5.2/lib/src/constants.dart b/json_serializable-3.5.2/lib/src/constants.dart new file mode 100644 index 000000000..2a4b34de3 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/constants.dart @@ -0,0 +1,9 @@ +// 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. + +/// Name used for closure argument when generating calls to `map`. +const closureArg = 'e'; + +const generatedLocalVarName = 'val'; +const toJsonMapHelperName = 'writeNotNull'; diff --git a/json_serializable-3.5.2/lib/src/decode_helper.dart b/json_serializable-3.5.2/lib/src/decode_helper.dart new file mode 100644 index 000000000..1d18e69a5 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/decode_helper.dart @@ -0,0 +1,323 @@ +// 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. + +import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/nullability_suffix.dart'; +import 'package:build/build.dart'; +import 'package:source_gen/source_gen.dart'; + +import 'helper_core.dart'; +import 'json_literal_generator.dart'; +import 'type_helpers/generic_factory_helper.dart'; +import 'unsupported_type_error.dart'; +import 'utils.dart'; + +class CreateFactoryResult { + final String output; + final Set usedFields; + + CreateFactoryResult(this.output, this.usedFields); +} + +abstract class DecodeHelper implements HelperCore { + CreateFactoryResult createFactory( + Map accessibleFields, + Map unavailableReasons, + ) { + assert(config.createFactory); + final buffer = StringBuffer(); + + final mapType = config.anyMap ? 'Map' : 'Map'; + buffer.write('$targetClassReference ' + '${prefix}FromJson${genericClassArgumentsImpl(true)}' + '($mapType json'); + + if (config.genericArgumentFactories) { + for (var arg in element.typeParameters) { + final helperName = fromJsonForType( + arg.instantiate(nullabilitySuffix: NullabilitySuffix.none), + ); + + buffer.write(', ${arg.name} Function(Object json) $helperName'); + } + if (element.typeParameters.isNotEmpty) { + buffer.write(','); + } + } + + buffer.write(') {\n'); + + String deserializeFun(String paramOrFieldName, + {ParameterElement ctorParam}) => + _deserializeForField(accessibleFields[paramOrFieldName], + ctorParam: ctorParam); + + final data = _writeConstructorInvocation( + element, + accessibleFields.keys, + accessibleFields.values + .where((fe) => + !fe.isFinal || + // Handle the case where `fe` defines a getter in `element` + // and there is a setter in a super class + // See google/json_serializable.dart#613 + element.lookUpSetter(fe.name, element.library) != null) + .map((fe) => fe.name) + .toList(), + unavailableReasons, + deserializeFun, + ); + + final checks = _checkKeys(accessibleFields.values + .where((fe) => data.usedCtorParamsAndFields.contains(fe.name))); + + if (config.checked) { + final classLiteral = escapeDartString(element.name); + + buffer..write(''' + return \$checkedNew( + $classLiteral, + json, + () {\n''')..write(checks)..write(''' + final val = ${data.content};'''); + + for (final field in data.fieldsToSet) { + buffer.writeln(); + final safeName = safeNameAccess(accessibleFields[field]); + buffer + ..write(''' + \$checkedConvert(json, $safeName, (v) => ''') + ..write('val.$field = ') + ..write(_deserializeForField(accessibleFields[field], + checkedProperty: true)) + ..write(');'); + } + + buffer.write('''\n return val; + }'''); + + final fieldKeyMap = Map.fromEntries(data.usedCtorParamsAndFields + .map((k) => MapEntry(k, nameAccess(accessibleFields[k]))) + .where((me) => me.key != me.value)); + + String fieldKeyMapArg; + if (fieldKeyMap.isEmpty) { + fieldKeyMapArg = ''; + } else { + final mapLiteral = jsonMapAsDart(fieldKeyMap); + fieldKeyMapArg = ', fieldKeyMap: const $mapLiteral'; + } + + buffer..write(fieldKeyMapArg)..write(')'); + } else { + buffer..write(checks)..write(''' + return ${data.content}'''); + for (final field in data.fieldsToSet) { + buffer + ..writeln() + ..write(' ..$field = ') + ..write(deserializeFun(field)); + } + } + buffer..writeln(';\n}')..writeln(); + + return CreateFactoryResult(buffer.toString(), data.usedCtorParamsAndFields); + } + + String _checkKeys(Iterable accessibleFields) { + final args = []; + + String constantList(Iterable things) => + 'const ${jsonLiteralAsDart(things.map(nameAccess).toList())}'; + + if (config.disallowUnrecognizedKeys) { + final allowKeysLiteral = constantList(accessibleFields); + + args.add('allowedKeys: $allowKeysLiteral'); + } + + final requiredKeys = + accessibleFields.where((fe) => jsonKeyFor(fe).required).toList(); + if (requiredKeys.isNotEmpty) { + final requiredKeyLiteral = constantList(requiredKeys); + + args.add('requiredKeys: $requiredKeyLiteral'); + } + + final disallowNullKeys = accessibleFields + .where((fe) => jsonKeyFor(fe).disallowNullValue) + .toList(); + if (disallowNullKeys.isNotEmpty) { + final disallowNullKeyLiteral = constantList(disallowNullKeys); + + args.add('disallowNullValues: $disallowNullKeyLiteral'); + } + + if (args.isEmpty) { + return ''; + } else { + return '\$checkKeys(json, ${args.join(', ')});\n'; + } + } + + String _deserializeForField( + FieldElement field, { + ParameterElement ctorParam, + bool checkedProperty, + }) { + checkedProperty ??= false; + final jsonKeyName = safeNameAccess(field); + final targetType = ctorParam?.type ?? field.type; + final contextHelper = getHelperContext(field); + + String value; + try { + if (config.checked) { + value = contextHelper.deserialize(targetType, 'v').toString(); + if (!checkedProperty) { + value = '\$checkedConvert(json, $jsonKeyName, (v) => $value)'; + } + } else { + assert(!checkedProperty, + 'should only be true if `_generator.checked` is true.'); + + value = contextHelper + .deserialize(targetType, 'json[$jsonKeyName]') + .toString(); + } + } on UnsupportedTypeError catch (e) // ignore: avoid_catching_errors + { + throw createInvalidGenerationError('fromJson', field, e); + } + + final jsonKey = jsonKeyFor(field); + final defaultValue = jsonKey.defaultValue; + if (defaultValue != null) { + if (!contextHelper.nullable) { + throwUnsupported(field, + 'Cannot use `defaultValue` on a field with `nullable` false.'); + } + if (jsonKey.disallowNullValue && jsonKey.required) { + log.warning('The `defaultValue` on field `${field.name}` will have no ' + 'effect because both `disallowNullValue` and `required` are set to ' + '`true`.'); + } + if (contextHelper.deserializeConvertData != null) { + log.warning('The field `${field.name}` has both `defaultValue` and ' + '`fromJson` defined which likely won\'t work for your scenario.\n' + 'Instead of using `defaultValue`, set `nullable: false` and handle ' + '`null` in the `fromJson` function.'); + } + value = '$value ?? $defaultValue'; + } + return value; + } +} + +/// [availableConstructorParameters] is checked to see if it is available. If +/// [availableConstructorParameters] does not contain the parameter name, +/// an [UnsupportedError] is thrown. +/// +/// To improve the error details, [unavailableReasons] is checked for the +/// unavailable constructor parameter. If the value is not `null`, it is +/// included in the [UnsupportedError] message. +/// +/// [writableFields] are also populated, but only if they have not already +/// been defined by a constructor parameter with the same name. +_ConstructorData _writeConstructorInvocation( + ClassElement classElement, + Iterable availableConstructorParameters, + Iterable writableFields, + Map unavailableReasons, + String Function(String paramOrFieldName, {ParameterElement ctorParam}) + deserializeForField, +) { + final className = classElement.name; + + final ctor = classElement.unnamedConstructor; + if (ctor == null) { + // TODO: support using another ctor - google/json_serializable.dart#50 + throw InvalidGenerationSourceError( + 'The class `$className` has no default constructor.', + element: classElement); + } + + final usedCtorParamsAndFields = {}; + final constructorArguments = []; + final namedConstructorArguments = []; + + for (final arg in ctor.parameters) { + if (!availableConstructorParameters.contains(arg.name)) { + if (arg.isNotOptional) { + var msg = 'Cannot populate the required constructor ' + 'argument: ${arg.name}.'; + + final additionalInfo = unavailableReasons[arg.name]; + + if (additionalInfo != null) { + msg = '$msg $additionalInfo'; + } + + throw InvalidGenerationSourceError(msg, element: ctor); + } + + continue; + } + + // TODO: validate that the types match! + if (arg.isNamed) { + namedConstructorArguments.add(arg); + } else { + constructorArguments.add(arg); + } + usedCtorParamsAndFields.add(arg.name); + } + + // fields that aren't already set by the constructor and that aren't final + final remainingFieldsForInvocationBody = + writableFields.toSet().difference(usedCtorParamsAndFields); + + final buffer = StringBuffer() + ..write('$className${genericClassArguments(classElement, false)}('); + if (constructorArguments.isNotEmpty) { + buffer + ..writeln() + ..writeAll(constructorArguments.map((paramElement) { + final content = + deserializeForField(paramElement.name, ctorParam: paramElement); + return ' $content,\n'; + })); + } + if (namedConstructorArguments.isNotEmpty) { + buffer + ..writeln() + ..writeAll(namedConstructorArguments.map((paramElement) { + final value = + deserializeForField(paramElement.name, ctorParam: paramElement); + return ' ${paramElement.name}: $value,\n'; + })); + } + + buffer.write(')'); + + usedCtorParamsAndFields.addAll(remainingFieldsForInvocationBody); + + return _ConstructorData( + buffer.toString(), + remainingFieldsForInvocationBody, + usedCtorParamsAndFields, + ); +} + +class _ConstructorData { + final String content; + final Set fieldsToSet; + final Set usedCtorParamsAndFields; + + _ConstructorData( + this.content, + this.fieldsToSet, + this.usedCtorParamsAndFields, + ); +} diff --git a/json_serializable-3.5.2/lib/src/encoder_helper.dart b/json_serializable-3.5.2/lib/src/encoder_helper.dart new file mode 100644 index 000000000..806737481 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/encoder_helper.dart @@ -0,0 +1,156 @@ +// 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. + +import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/nullability_suffix.dart'; +import 'package:json_annotation/json_annotation.dart'; + +import 'constants.dart'; +import 'helper_core.dart'; +import 'type_helpers/generic_factory_helper.dart'; +import 'type_helpers/json_converter_helper.dart'; +import 'unsupported_type_error.dart'; + +abstract class EncodeHelper implements HelperCore { + String _fieldAccess(FieldElement field) => '$_toJsonParamName.${field.name}'; + + Iterable createToJson(Set accessibleFields) sync* { + assert(config.createToJson); + + final buffer = StringBuffer(); + + final functionName = '${prefix}ToJson${genericClassArgumentsImpl(true)}'; + buffer.write('Map ' + '$functionName($targetClassReference $_toJsonParamName'); + + if (config.genericArgumentFactories) { + for (var arg in element.typeParameters) { + final helperName = toJsonForType( + arg.instantiate(nullabilitySuffix: NullabilitySuffix.none), + ); + buffer.write(',Object Function(${arg.name} value) $helperName'); + } + if (element.typeParameters.isNotEmpty) { + buffer.write(','); + } + } + buffer.write(') '); + + final writeNaive = accessibleFields.every(_writeJsonValueNaive); + + if (writeNaive) { + // write simple `toJson` method that includes all keys... + _writeToJsonSimple(buffer, accessibleFields); + } else { + // At least one field should be excluded if null + _writeToJsonWithNullChecks(buffer, accessibleFields); + } + + yield buffer.toString(); + } + + void _writeToJsonSimple(StringBuffer buffer, Iterable fields) { + buffer + ..writeln('=> {') + ..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 fields, + ) { + buffer + ..writeln('{') + ..writeln(' final $generatedLocalVarName = {'); + + // 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 (_writeJsonValueNaive(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) + .serialize(field.type, accessExpression) + .toString(); + } on UnsupportedTypeError catch (e) // ignore: avoid_catching_errors + { + throw createInvalidGenerationError('toJson', field, e); + } + } + + /// Returns `true` if the field can be written to JSON 'naively' – meaning + /// we can avoid checking for `null`. + bool _writeJsonValueNaive(FieldElement field) { + final jsonKey = jsonKeyFor(field); + return jsonKey.includeIfNull || + (!jsonKey.nullable && !_fieldHasCustomEncoder(field)); + } + + /// Returns `true` if [field] has a user-defined encoder. + /// + /// This can be either a `toJson` function in [JsonKey] or a [JsonConverter] + /// annotation. + bool _fieldHasCustomEncoder(FieldElement field) { + final helperContext = getHelperContext(field); + return helperContext.serializeConvertData != null || + const JsonConverterHelper() + .serialize(field.type, 'test', helperContext) != + null; + } +} diff --git a/json_serializable-3.5.2/lib/src/field_helpers.dart b/json_serializable-3.5.2/lib/src/field_helpers.dart new file mode 100644 index 000000000..932c43df5 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/field_helpers.dart @@ -0,0 +1,111 @@ +// 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. + +import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/src/dart/element/inheritance_manager3.dart' // ignore: implementation_imports + show + InheritanceManager3; +import 'package:source_gen/source_gen.dart'; + +import 'utils.dart'; + +class _FieldSet implements Comparable<_FieldSet> { + final FieldElement field; + final FieldElement sortField; + + _FieldSet._(this.field, this.sortField) + : assert(field.name == sortField.name); + + factory _FieldSet(FieldElement classField, FieldElement superField) { + // At least one of these will != null, perhaps both. + final fields = [classField, superField].where((fe) => fe != null).toList(); + + // Prefer the class field over the inherited field when sorting. + final sortField = fields.first; + + // Prefer the field that's annotated with `JsonKey`, if any. + // If not, use the class field. + final fieldHasJsonKey = + fields.firstWhere(hasJsonKeyAnnotation, orElse: () => fields.first); + + return _FieldSet._(fieldHasJsonKey, sortField); + } + + @override + int compareTo(_FieldSet other) => _sortByLocation(sortField, other.sortField); + + static int _sortByLocation(FieldElement a, FieldElement b) { + final checkerA = + TypeChecker.fromStatic((a.enclosingElement as ClassElement).thisType); + + if (!checkerA.isExactly(b.enclosingElement)) { + // in this case, you want to prioritize the enclosingElement that is more + // "super". + + if (checkerA.isAssignableFrom(b.enclosingElement)) { + return -1; + } + + final checkerB = + TypeChecker.fromStatic((b.enclosingElement as ClassElement).thisType); + + if (checkerB.isAssignableFrom(a.enclosingElement)) { + return 1; + } + } + + /// Returns the offset of given field/property in its source file – with a + /// preference for the getter if it's defined. + int _offsetFor(FieldElement e) { + if (e.getter != null && e.getter.nameOffset != e.nameOffset) { + assert(e.nameOffset == -1); + return e.getter.nameOffset; + } + return e.nameOffset; + } + + return _offsetFor(a).compareTo(_offsetFor(b)); + } +} + +/// Returns a [Set] of all instance [FieldElement] items for [element] and +/// super classes, sorted first by their location in the inheritance hierarchy +/// (super first) and then by their location in the source file. +Iterable createSortedFieldSet(ClassElement element) { + // Get all of the fields that need to be assigned + // TODO: support overriding the field set with an annotation option + final elementInstanceFields = Map.fromEntries( + element.fields.where((e) => !e.isStatic).map((e) => MapEntry(e.name, e))); + + final inheritedFields = {}; + final manager = InheritanceManager3(); + + // ignore: deprecated_member_use + for (final v in manager.getInheritedConcreteMap(element.thisType).values) { + assert(v is! FieldElement); + if (_dartCoreObjectChecker.isExactly(v.enclosingElement)) { + continue; + } + + if (v is PropertyAccessorElement && v.isGetter) { + assert(v.variable is FieldElement); + final variable = v.variable as FieldElement; + assert(!inheritedFields.containsKey(variable.name)); + inheritedFields[variable.name] = variable; + } + } + + // Get the list of all fields for `element` + final allFields = + elementInstanceFields.keys.toSet().union(inheritedFields.keys.toSet()); + + final fields = allFields + .map((e) => _FieldSet(elementInstanceFields[e], inheritedFields[e])) + .toList() + ..sort(); + + return fields.map((fs) => fs.field).toList(); +} + +const _dartCoreObjectChecker = TypeChecker.fromRuntime(Object); diff --git a/json_serializable-3.5.2/lib/src/generator_helper.dart b/json_serializable-3.5.2/lib/src/generator_helper.dart new file mode 100644 index 000000000..011fd46d3 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/generator_helper.dart @@ -0,0 +1,117 @@ +// Copyright (c) 2020, 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. + +import 'package:analyzer/dart/element/element.dart'; +import 'package:build/build.dart'; +import 'package:source_gen/source_gen.dart'; + +import 'decode_helper.dart'; +import 'encoder_helper.dart'; +import 'field_helpers.dart'; +import 'helper_core.dart'; +import 'settings.dart'; +import 'type_helper.dart'; +import 'utils.dart'; + +class GeneratorHelper extends HelperCore with EncodeHelper, DecodeHelper { + final Settings _generator; + final _addedMembers = {}; + + GeneratorHelper( + this._generator, + ClassElement element, + ConstantReader annotation, + ) : super( + element, + mergeConfig( + _generator.config, + annotation, + classElement: element, + )); + + @override + void addMember(String memberContent) { + _addedMembers.add(memberContent); + } + + @override + Iterable get allTypeHelpers => _generator.allHelpers; + + Iterable generate() sync* { + assert(_addedMembers.isEmpty); + + if (config.genericArgumentFactories && element.typeParameters.isEmpty) { + log.warning( + 'The class `${element.displayName}` is annotated ' + 'with `JsonSerializable` field `genericArgumentFactories: true`. ' + '`genericArgumentFactories: true` only affects classes with type ' + 'parameters. For classes without type parameters, the option is ' + 'ignored.', + ); + } + + final sortedFields = createSortedFieldSet(element); + + // Used to keep track of why a field is ignored. Useful for providing + // helpful errors when generating constructor calls that try to use one of + // these fields. + final unavailableReasons = {}; + + final accessibleFields = sortedFields.fold>( + {}, + (map, field) { + if (!field.isPublic) { + unavailableReasons[field.name] = 'It is assigned to a private field.'; + } else if (field.getter == null) { + assert(field.setter != null); + unavailableReasons[field.name] = + 'Setter-only properties are not supported.'; + log.warning('Setters are ignored: ${element.name}.${field.name}'); + } else if (jsonKeyFor(field).ignore) { + unavailableReasons[field.name] = + 'It is assigned to an ignored field.'; + } else { + assert(!map.containsKey(field.name)); + map[field.name] = field; + } + + return map; + }, + ); + + var accessibleFieldSet = accessibleFields.values.toSet(); + if (config.createFactory) { + final createResult = createFactory(accessibleFields, unavailableReasons); + yield createResult.output; + + accessibleFieldSet = accessibleFields.entries + .where((e) => createResult.usedFields.contains(e.key)) + .map((e) => e.value) + .toSet(); + } + + // Check for duplicate JSON keys due to colliding annotations. + // We do this now, since we have a final field list after any pruning done + // by `_writeCtor`. + accessibleFieldSet.fold( + {}, + (Set set, fe) { + final jsonKey = nameAccess(fe); + if (!set.add(jsonKey)) { + throw InvalidGenerationSourceError( + 'More than one field has the JSON key for name "$jsonKey".', + element: fe, + ); + } + return set; + }, + ); + + if (config.createToJson) { + yield* createToJson(accessibleFieldSet); + } + + yield* _addedMembers; + } +} diff --git a/json_serializable-3.5.2/lib/src/helper_core.dart b/json_serializable-3.5.2/lib/src/helper_core.dart new file mode 100644 index 000000000..ebd56fc0b --- /dev/null +++ b/json_serializable-3.5.2/lib/src/helper_core.dart @@ -0,0 +1,156 @@ +// 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. + +import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/type.dart'; +import 'package:json_annotation/json_annotation.dart'; +import 'package:meta/meta.dart'; +import 'package:source_gen/source_gen.dart'; + +import 'json_key_utils.dart'; +import 'type_helper.dart'; +import 'type_helper_ctx.dart'; +import 'unsupported_type_error.dart'; +import 'utils.dart'; + +abstract class HelperCore { + final ClassElement element; + final JsonSerializable config; + + HelperCore(this.element, this.config); + + Iterable get allTypeHelpers; + + void addMember(String memberContent); + + @protected + String get targetClassReference => + '${element.name}${genericClassArgumentsImpl(false)}'; + + @protected + String nameAccess(FieldElement field) => jsonKeyFor(field).name; + + @protected + String safeNameAccess(FieldElement field) => + escapeDartString(nameAccess(field)); + + @protected + String get prefix => '_\$${element.name}'; + + /// Returns a [String] representing the type arguments that exist on + /// [element]. + /// + /// Returns the output of calling [genericClassArguments] with [element]. + @protected + String genericClassArgumentsImpl(bool withConstraints) => + genericClassArguments(element, withConstraints); + + @protected + JsonKey jsonKeyFor(FieldElement field) => jsonKeyForField(field, config); + + @protected + TypeHelperCtx getHelperContext(FieldElement field) => + typeHelperContext(this, field, jsonKeyFor(field)); +} + +InvalidGenerationSourceError createInvalidGenerationError( + String targetMember, + FieldElement field, + UnsupportedTypeError error, +) { + var message = 'Could not generate `$targetMember` code for `${field.name}`'; + + String todo; + if (error.type is TypeParameterType) { + message = '$message because of type ' + '`${error.type.getDisplayString(withNullability: false)}` (type parameter)'; + + todo = ''' +To support type parameters (generic types) you can: +$converterOrKeyInstructions +* Set `JsonSerializable.genericArgumentFactories` to `true` + https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonSerializable/genericArgumentFactories.html'''; + } else if (field.type != error.type) { + message = '$message because of type `${typeToCode(error.type)}`'; + } else { + todo = ''' +To support the type `${error.type.element.name}` you can: +$converterOrKeyInstructions'''; + } + + return InvalidGenerationSourceError( + [ + '$message.', + if (error.reason != null) error.reason, + if (todo != null) todo, + ].join('\n'), + element: field, + ); +} + +@visibleForTesting +const converterOrKeyInstructions = r''' +* Use `JsonConverter` + https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonConverter-class.html +* Use `JsonKey` fields `fromJson` and `toJson` + https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/fromJson.html + https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/toJson.html'''; + +/// Returns a [String] representing the type arguments that exist on +/// [element]. +/// +/// If [withConstraints] is `null` or if [element] has no type arguments, an +/// empty [String] is returned. +/// +/// If [withConstraints] is true, any type constraints that exist on [element] +/// are included. +/// +/// For example, for class `class Sample{...}` +/// +/// For [withConstraints] = `false`: +/// +/// ``` +/// "" +/// ``` +/// +/// For [withConstraints] = `true`: +/// +/// ``` +/// "" +/// ``` +String genericClassArguments(ClassElement element, bool withConstraints) { + if (withConstraints == null || element.typeParameters.isEmpty) { + return ''; + } + final values = element.typeParameters.map((t) { + if (withConstraints && t.bound != null) { + final boundCode = typeToCode(t.bound); + return '${t.name} extends $boundCode'; + } else { + return t.name; + } + }).join(', '); + return '<$values>'; +} + +/// Return the Dart code presentation for the given [type]. +/// +/// This function is intentionally limited, and does not support all possible +/// types and locations of these files in code. Specifically, it supports +/// only [InterfaceType]s, with optional type arguments that are also should +/// be [InterfaceType]s. +String typeToCode(DartType type) { + if (type.isDynamic) { + return 'dynamic'; + } else if (type is InterfaceType) { + final typeArguments = type.typeArguments; + if (typeArguments.isEmpty) { + return type.element.name; + } else { + final typeArgumentsCode = typeArguments.map(typeToCode).join(', '); + return '${type.element.name}<$typeArgumentsCode>'; + } + } + throw UnimplementedError('(${type.runtimeType}) $type'); +} diff --git a/json_serializable-3.5.2/lib/src/json_key_utils.dart b/json_serializable-3.5.2/lib/src/json_key_utils.dart new file mode 100644 index 000000000..cd6a42f0c --- /dev/null +++ b/json_serializable-3.5.2/lib/src/json_key_utils.dart @@ -0,0 +1,279 @@ +// 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. + +import 'package:analyzer/dart/constant/value.dart'; +import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/type.dart'; +import 'package:build/build.dart'; +import 'package:json_annotation/json_annotation.dart'; +import 'package:source_gen/source_gen.dart'; + +import 'json_literal_generator.dart'; +import 'shared_checkers.dart'; +import 'utils.dart'; + +final _jsonKeyExpando = Expando(); + +JsonKey jsonKeyForField(FieldElement field, JsonSerializable classAnnotation) => + _jsonKeyExpando[field] ??= _from(field, classAnnotation); + +/// Will log "info" if [element] has an explicit value for [JsonKey.nullable] +/// telling the programmer that it will be ignored. +void logFieldWithConversionFunction(FieldElement element) { + final jsonKey = _jsonKeyExpando[element]; + if (_explicitNullableExpando[jsonKey] ?? false) { + log.info( + 'The `JsonKey.nullable` value on ' + '`${element.enclosingElement.name}.${element.name}` will be ignored ' + 'because a custom conversion function is being used.', + ); + + _explicitNullableExpando[jsonKey] = null; + } +} + +JsonKey _from(FieldElement element, JsonSerializable classAnnotation) { + // If an annotation exists on `element` the source is a 'real' field. + // If the result is `null`, check the getter – it is a property. + // TODO: setters: github.com/google/json_serializable.dart/issues/24 + final obj = jsonKeyAnnotation(element); + + if (obj.isNull) { + return _populateJsonKey( + classAnnotation, + element, + ignore: classAnnotation.ignoreUnannotated, + ); + } + + /// Returns a literal value for [dartObject] if possible, otherwise throws + /// an [InvalidGenerationSourceError] using [typeInformation] to describe + /// the unsupported type. + Object literalForObject( + DartObject dartObject, + Iterable typeInformation, + ) { + if (dartObject.isNull) { + return null; + } + + final reader = ConstantReader(dartObject); + + String badType; + if (reader.isSymbol) { + badType = 'Symbol'; + } else if (reader.isType) { + badType = 'Type'; + } else if (dartObject.type is FunctionType) { + // TODO: Support calling function for the default value? + badType = 'Function'; + } else if (!reader.isLiteral) { + badType = dartObject.type.element.name; + } + + if (badType != null) { + badType = typeInformation.followedBy([badType]).join(' > '); + throwUnsupported( + element, '`defaultValue` is `$badType`, it must be a literal.'); + } + + if (reader.isDouble || reader.isInt || reader.isString || reader.isBool) { + return reader.literalValue; + } + + if (reader.isList) { + return [ + for (var e in reader.listValue) + literalForObject(e, [ + ...typeInformation, + 'List', + ]) + ]; + } + + if (reader.isSet) { + return { + for (var e in reader.setValue) + literalForObject(e, [ + ...typeInformation, + 'Set', + ]) + }; + } + + if (reader.isMap) { + final mapTypeInformation = [ + ...typeInformation, + 'Map', + ]; + return reader.mapValue.map( + (k, v) => MapEntry( + literalForObject(k, mapTypeInformation), + literalForObject(v, mapTypeInformation), + ), + ); + } + + badType = typeInformation.followedBy(['$dartObject']).join(' > '); + + throwUnsupported( + element, + 'The provided value is not supported: $badType. ' + 'This may be an error in package:json_serializable. ' + 'Please rerun your build with `--verbose` and file an issue.', + ); + } + + /// Returns a literal object representing the value of [fieldName] in [obj]. + /// + /// If [mustBeEnum] is `true`, throws an [InvalidGenerationSourceError] if + /// either the annotated field is not an `enum` or `List` or if the value in + /// [fieldName] is not an `enum` value. + Object _annotationValue(String fieldName, {bool mustBeEnum = false}) { + final annotationValue = obj.read(fieldName); + + final enumFields = annotationValue.isNull + ? null + : iterateEnumFields(annotationValue.objectValue.type); + if (enumFields != null) { + if (mustBeEnum) { + DartType targetEnumType; + if (isEnum(element.type)) { + targetEnumType = element.type; + } else if (coreIterableTypeChecker.isAssignableFromType(element.type)) { + targetEnumType = coreIterableGenericType(element.type); + } else { + throwUnsupported( + element, + '`$fieldName` can only be set on fields of type enum or on ' + 'Iterable, List, or Set instances of an enum type.', + ); + } + assert(targetEnumType != null); + final annotatedEnumType = annotationValue.objectValue.type; + if (annotatedEnumType != targetEnumType) { + throwUnsupported( + element, + '`$fieldName` has type ' + '`${targetEnumType.getDisplayString(withNullability: false)}`, but ' + 'the provided unknownEnumValue is of type ' + '`${annotatedEnumType.getDisplayString(withNullability: false)}`.', + ); + } + } + + final enumValueNames = + enumFields.map((p) => p.name).toList(growable: false); + + final enumValueName = enumValueForDartObject( + annotationValue.objectValue, enumValueNames, (n) => n); + + return '${annotationValue.objectValue.type.element.name}.$enumValueName'; + } else { + final defaultValueLiteral = annotationValue.isNull + ? null + : literalForObject(annotationValue.objectValue, []); + if (defaultValueLiteral == null) { + return null; + } + if (mustBeEnum) { + throwUnsupported( + element, + 'The value provided for `$fieldName` must be a matching enum.', + ); + } + return jsonLiteralAsDart(defaultValueLiteral); + } + } + + return _populateJsonKey( + classAnnotation, + element, + defaultValue: _annotationValue('defaultValue'), + disallowNullValue: obj.read('disallowNullValue').literalValue as bool, + ignore: obj.read('ignore').literalValue as bool, + includeIfNull: obj.read('includeIfNull').literalValue as bool, + name: obj.read('name').literalValue as String, + nullable: obj.read('nullable').literalValue as bool, + required: obj.read('required').literalValue as bool, + unknownEnumValue: _annotationValue('unknownEnumValue', mustBeEnum: true), + ); +} + +JsonKey _populateJsonKey( + JsonSerializable classAnnotation, + FieldElement element, { + Object defaultValue, + bool disallowNullValue, + bool ignore, + bool includeIfNull, + String name, + bool nullable, + bool required, + Object unknownEnumValue, +}) { + if (disallowNullValue == true) { + if (includeIfNull == true) { + throwUnsupported( + element, + 'Cannot set both `disallowNullvalue` and `includeIfNull` to `true`. ' + 'This leads to incompatible `toJson` and `fromJson` behavior.'); + } + } + + final jsonKey = JsonKey( + defaultValue: defaultValue, + disallowNullValue: disallowNullValue ?? false, + ignore: ignore ?? false, + includeIfNull: _includeIfNull( + includeIfNull, disallowNullValue, classAnnotation.includeIfNull), + name: _encodedFieldName(classAnnotation, name, element), + nullable: nullable ?? classAnnotation.nullable, + required: required ?? false, + unknownEnumValue: unknownEnumValue, + ); + + _explicitNullableExpando[jsonKey] = nullable != null; + + return jsonKey; +} + +final _explicitNullableExpando = Expando('explicit nullable'); + +String _encodedFieldName(JsonSerializable classAnnotation, + String jsonKeyNameValue, FieldElement fieldElement) { + if (jsonKeyNameValue != null) { + return jsonKeyNameValue; + } + + switch (classAnnotation.fieldRename) { + case FieldRename.none: + return fieldElement.name; + case FieldRename.snake: + return snakeCase(fieldElement.name); + case FieldRename.kebab: + return kebabCase(fieldElement.name); + case FieldRename.pascal: + return pascalCase(fieldElement.name); + } + + throw ArgumentError.value( + classAnnotation, + 'classAnnotation', + 'The provided `fieldRename` (${classAnnotation.fieldRename}) is not ' + 'supported.', + ); +} + +bool _includeIfNull( + bool keyIncludeIfNull, + bool keyDisallowNullValue, + bool classIncludeIfNull, +) { + if (keyDisallowNullValue == true) { + assert(keyIncludeIfNull != true); + return false; + } + return keyIncludeIfNull ?? classIncludeIfNull; +} diff --git a/json_serializable-3.5.2/lib/src/json_literal_generator.dart b/json_serializable-3.5.2/lib/src/json_literal_generator.dart new file mode 100644 index 000000000..cf01a6852 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/json_literal_generator.dart @@ -0,0 +1,100 @@ +// Copyright (c) 2017, 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. + +import 'dart:async'; +import 'dart:convert'; + +import 'package:analyzer/dart/element/element.dart'; +import 'package:build/build.dart'; +import 'package:json_annotation/json_annotation.dart'; +import 'package:path/path.dart' as p; +import 'package:source_gen/source_gen.dart'; + +import 'utils.dart'; + +class JsonLiteralGenerator extends GeneratorForAnnotation { + const JsonLiteralGenerator(); + + @override + Future generateForAnnotatedElement( + Element element, + ConstantReader annotation, + BuildStep buildStep, + ) async { + if (p.isAbsolute(annotation.read('path').stringValue)) { + throw ArgumentError( + '`annotation.path` must be relative path to the source file.'); + } + + final sourcePathDir = p.dirname(buildStep.inputId.path); + final fileId = AssetId(buildStep.inputId.package, + p.join(sourcePathDir, annotation.read('path').stringValue)); + final content = json.decode(await buildStep.readAsString(fileId)); + + final asConst = annotation.read('asConst').boolValue; + + final thing = jsonLiteralAsDart(content).toString(); + final marked = asConst ? 'const' : 'final'; + + return '$marked _\$${element.name}JsonLiteral = $thing;'; + } +} + +/// Returns a [String] representing a valid Dart literal for [value]. +String jsonLiteralAsDart(dynamic value) { + if (value == null) return 'null'; + + if (value is String) return escapeDartString(value); + + if (value is double) { + if (value.isNaN) { + return 'double.nan'; + } + + if (value.isInfinite) { + if (value.isNegative) { + return 'double.negativeInfinity'; + } + return 'double.infinity'; + } + } + + if (value is bool || value is num) return value.toString(); + + if (value is List) { + final listItems = value.map(jsonLiteralAsDart).join(', '); + return '[$listItems]'; + } + + if (value is Set) { + final listItems = value.map(jsonLiteralAsDart).join(', '); + return '{$listItems}'; + } + + if (value is Map) return jsonMapAsDart(value); + + throw StateError( + 'Should never get here – with ${value.runtimeType} - `$value`.'); +} + +String jsonMapAsDart(Map value) { + final buffer = StringBuffer()..write('{'); + + var first = true; + value.forEach((k, v) { + if (first) { + first = false; + } else { + buffer.writeln(','); + } + buffer + ..write(escapeDartString(k as String)) + ..write(': ') + ..write(jsonLiteralAsDart(v)); + }); + + buffer.write('}'); + + return buffer.toString(); +} diff --git a/json_serializable-3.5.2/lib/src/json_part_builder.dart b/json_serializable-3.5.2/lib/src/json_part_builder.dart new file mode 100644 index 000000000..1bf2d38f3 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/json_part_builder.dart @@ -0,0 +1,32 @@ +// Copyright (c) 2017, 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. + +import 'package:build/build.dart'; +import 'package:json_annotation/json_annotation.dart'; +import 'package:source_gen/source_gen.dart'; + +import 'json_literal_generator.dart'; +import 'json_serializable_generator.dart'; +import 'settings.dart'; + +/// Returns a [Builder] for use within a `package:build_runner` +/// `BuildAction`. +/// +/// [formatOutput] is called to format the generated code. If not provided, +/// the default Dart code formatter is used. +Builder jsonPartBuilder({ + String Function(String code) formatOutput, + JsonSerializable config, +}) { + final settings = Settings(config: config); + + return SharedPartBuilder( + [ + JsonSerializableGenerator.fromSettings(settings), + const JsonLiteralGenerator(), + ], + 'json_serializable', + formatOutput: formatOutput, + ); +} diff --git a/json_serializable-3.5.2/lib/src/json_serializable_generator.dart b/json_serializable-3.5.2/lib/src/json_serializable_generator.dart new file mode 100644 index 000000000..244017aeb --- /dev/null +++ b/json_serializable-3.5.2/lib/src/json_serializable_generator.dart @@ -0,0 +1,75 @@ +// Copyright (c) 2017, 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. + +import 'package:analyzer/dart/element/element.dart'; +import 'package:build/build.dart'; +import 'package:json_annotation/json_annotation.dart'; +import 'package:source_gen/source_gen.dart'; + +import 'generator_helper.dart'; +import 'settings.dart'; +import 'type_helper.dart'; +import 'type_helpers/big_int_helper.dart'; +import 'type_helpers/date_time_helper.dart'; +import 'type_helpers/duration_helper.dart'; +import 'type_helpers/json_helper.dart'; +import 'type_helpers/uri_helper.dart'; + +class JsonSerializableGenerator + extends GeneratorForAnnotation { + final Settings _settings; + + JsonSerializable get config => _settings.config; + + JsonSerializableGenerator.fromSettings(this._settings); + + /// Creates an instance of [JsonSerializableGenerator]. + /// + /// If [typeHelpers] is not provided, the built-in helpers are used: + /// [BigIntHelper], [DateTimeHelper], [DurationHelper], [JsonHelper], and + /// [UriHelper]. + factory JsonSerializableGenerator({ + JsonSerializable config, + List typeHelpers, + }) => + JsonSerializableGenerator.fromSettings(Settings( + config: config, + typeHelpers: typeHelpers, + )); + + /// Creates an instance of [JsonSerializableGenerator]. + /// + /// [typeHelpers] provides a set of [TypeHelper] that will be used along with + /// the built-in helpers: + /// [BigIntHelper], [DateTimeHelper], [DurationHelper], [JsonHelper], and + /// [UriHelper]. + factory JsonSerializableGenerator.withDefaultHelpers( + Iterable typeHelpers, { + JsonSerializable config, + }) => + JsonSerializableGenerator( + config: config, + typeHelpers: List.unmodifiable( + typeHelpers.followedBy(Settings.defaultHelpers), + ), + ); + + @override + Iterable generateForAnnotatedElement( + Element element, + ConstantReader annotation, + BuildStep buildStep, + ) { + if (element is! ClassElement) { + throw InvalidGenerationSourceError( + '`@JsonSerializable` can only be used on classes.', + element: element, + ); + } + + final classElement = element as ClassElement; + final helper = GeneratorHelper(_settings, classElement, annotation); + return helper.generate(); + } +} diff --git a/json_serializable-3.5.2/lib/src/lambda_result.dart b/json_serializable-3.5.2/lib/src/lambda_result.dart new file mode 100644 index 000000000..b87f433de --- /dev/null +++ b/json_serializable-3.5.2/lib/src/lambda_result.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2019, 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. + +class LambdaResult { + final String expression; + final String lambda; + + LambdaResult(this.expression, this.lambda); + + @override + String toString() => '$lambda($expression)'; + + static String process(Object subField, String closureArg) => + (subField is LambdaResult && closureArg == subField.expression) + ? subField.lambda + : '($closureArg) => $subField'; +} diff --git a/json_serializable-3.5.2/lib/src/settings.dart b/json_serializable-3.5.2/lib/src/settings.dart new file mode 100644 index 000000000..50b6639de --- /dev/null +++ b/json_serializable-3.5.2/lib/src/settings.dart @@ -0,0 +1,74 @@ +// Copyright (c) 2017, 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. + +import 'package:json_annotation/json_annotation.dart'; + +import 'type_helper.dart'; +import 'type_helpers/big_int_helper.dart'; +import 'type_helpers/convert_helper.dart'; +import 'type_helpers/date_time_helper.dart'; +import 'type_helpers/duration_helper.dart'; +import 'type_helpers/enum_helper.dart'; +import 'type_helpers/generic_factory_helper.dart'; +import 'type_helpers/iterable_helper.dart'; +import 'type_helpers/json_converter_helper.dart'; +import 'type_helpers/json_helper.dart'; +import 'type_helpers/map_helper.dart'; +import 'type_helpers/uri_helper.dart'; +import 'type_helpers/value_helper.dart'; + +class Settings { + static const _coreHelpers = [ + IterableHelper(), + MapHelper(), + EnumHelper(), + ValueHelper(), + ]; + + static const defaultHelpers = [ + BigIntHelper(), + DateTimeHelper(), + DurationHelper(), + JsonHelper(), + UriHelper(), + ]; + + final List _typeHelpers; + + Iterable get allHelpers => const [ + ConvertHelper(), + JsonConverterHelper(), + GenericFactoryHelper(), + ].followedBy(_typeHelpers).followedBy(_coreHelpers); + + final JsonSerializable _config; + + JsonSerializable get config => _config.withDefaults(); + + /// Creates an instance of [Settings]. + /// + /// If [typeHelpers] is not provided, the built-in helpers are used: + /// [BigIntHelper], [DateTimeHelper], [DurationHelper], [JsonHelper], and + /// [UriHelper]. + const Settings({ + JsonSerializable config, + List typeHelpers, + }) : _config = config ?? JsonSerializable.defaults, + _typeHelpers = typeHelpers ?? defaultHelpers; + + /// Creates an instance of [Settings]. + /// + /// [typeHelpers] provides a set of [TypeHelper] that will be used along with + /// the built-in helpers: + /// [BigIntHelper], [DateTimeHelper], [DurationHelper], [JsonHelper], and + /// [UriHelper]. + factory Settings.withDefaultHelpers( + Iterable typeHelpers, { + JsonSerializable config, + }) => + Settings( + config: config, + typeHelpers: List.unmodifiable(typeHelpers.followedBy(defaultHelpers)), + ); +} diff --git a/json_serializable-3.5.2/lib/src/shared_checkers.dart b/json_serializable-3.5.2/lib/src/shared_checkers.dart new file mode 100644 index 000000000..2a63a477e --- /dev/null +++ b/json_serializable-3.5.2/lib/src/shared_checkers.dart @@ -0,0 +1,85 @@ +// 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. + +import 'package:analyzer/dart/element/type.dart'; +import 'package:source_gen/source_gen.dart' show TypeChecker; + +import 'helper_core.dart'; + +/// A [TypeChecker] for [Iterable]. +const coreIterableTypeChecker = TypeChecker.fromUrl('dart:core#Iterable'); + +const coreStringTypeChecker = TypeChecker.fromUrl('dart:core#String'); + +const coreMapTypeChecker = TypeChecker.fromUrl('dart:core#Map'); + +/// Returns the generic type of the [Iterable] represented by [type]. +/// +/// If [type] does not extend [Iterable], an error is thrown. +DartType coreIterableGenericType(DartType type) => + typeArgumentsOf(type, coreIterableTypeChecker).single; + +/// If [type] is the [Type] or implements the [Type] represented by [checker], +/// returns the generic arguments to the [checker] [Type] if there are any. +/// +/// If the [checker] [Type] doesn't have generic arguments, `null` is returned. +List typeArgumentsOf(DartType type, TypeChecker checker) { + final implementation = _getImplementationType(type, checker) as InterfaceType; + + return implementation?.typeArguments; +} + +/// A [TypeChecker] for [String], [bool] and [num]. +const simpleJsonTypeChecker = TypeChecker.any([ + coreStringTypeChecker, + TypeChecker.fromUrl('dart:core#bool'), + TypeChecker.fromUrl('dart:core#num') +]); + +String asStatement(DartType type) { + if (isObjectOrDynamic(type)) { + return ''; + } + + if (coreIterableTypeChecker.isAssignableFromType(type)) { + final itemType = coreIterableGenericType(type); + if (isObjectOrDynamic(itemType)) { + return ' as List'; + } + } + + if (coreMapTypeChecker.isAssignableFromType(type)) { + final args = typeArgumentsOf(type, coreMapTypeChecker); + assert(args.length == 2); + + if (args.every(isObjectOrDynamic)) { + return ' as Map'; + } + } + + final typeCode = typeToCode(type); + return ' as $typeCode'; +} + +bool isObjectOrDynamic(DartType type) => + type.isDartCoreObject || type.isDynamic; + +/// Returns all of the [DartType] types that [type] implements, mixes-in, and +/// extends, starting with [type] itself. +Iterable typeImplementations(DartType type) sync* { + yield type; + + if (type is InterfaceType) { + yield* type.interfaces.expand(typeImplementations); + yield* type.mixins.expand(typeImplementations); + + if (type.superclass != null) { + yield* typeImplementations(type.superclass); + } + } +} + +DartType _getImplementationType(DartType type, TypeChecker checker) => + typeImplementations(type) + .firstWhere(checker.isExactlyType, orElse: () => null); diff --git a/json_serializable-3.5.2/lib/src/type_helper.dart b/json_serializable-3.5.2/lib/src/type_helper.dart new file mode 100644 index 000000000..cef3d4afb --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helper.dart @@ -0,0 +1,92 @@ +// Copyright (c) 2017, 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. + +import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/type.dart'; +import 'package:json_annotation/json_annotation.dart'; + +/// Context information provided in calls to [TypeHelper.serialize] and +/// [TypeHelper.deserialize]. +abstract class TypeHelperContext { + /// The annotated class that code is being generated for. + ClassElement get classElement; + + /// The field that code is being generated for. + FieldElement get fieldElement; + + /// Returns `true` if [fieldElement] could potentially contain a `null` value. + bool get nullable; + + /// [expression] may be just the name of the field or it may an expression + /// representing the serialization of a value. + Object serialize(DartType fieldType, String expression); + + /// [expression] may be just the name of the field or it may an expression + /// representing the serialization of a value. + Object deserialize(DartType fieldType, String expression); + + /// Adds [memberContent] to the set of generated, top-level members. + void addMember(String memberContent); +} + +/// Extended context information with includes configuration values +/// corresponding to `JsonSerializableGenerator` settings. +abstract class TypeHelperContextWithConfig extends TypeHelperContext { + JsonSerializable get config; +} + +abstract class TypeHelper { + const TypeHelper(); + + /// Returns Dart code that serializes an [expression] representing a Dart + /// object of type [targetType]. + /// + /// If [targetType] is not supported, returns `null`. + /// + /// Let's say you want to serialize a class `Foo` as just its `id` property + /// of type `int`. + /// + /// Treating [expression] as a opaque Dart expression, the [serialize] + /// implementation could be a simple as: + /// + /// ```dart + /// String serialize(DartType targetType, String expression) => + /// "$expression.id"; + /// ```. + Object serialize(DartType targetType, String expression, T context); + + /// Returns Dart code that deserializes an [expression] representing a JSON + /// literal to into [targetType]. + /// + /// If [targetType] is not supported, returns `null`. + /// + /// Let's say you want to deserialize a class `Foo` by taking an `int` stored + /// in a JSON literal and calling the `Foo.fromInt` constructor. + /// + /// Treating [expression] as a opaque Dart expression representing a JSON + /// literal, the [deserialize] implementation could be a simple as: + /// + /// ```dart + /// String deserialize(DartType targetType, String expression) => + /// "new Foo.fromInt($expression)"; + /// ```. + /// + /// Note that [targetType] is not used here. If you wanted to support many + /// types of [targetType] you could write: + /// + /// ```dart + /// String deserialize(DartType targetType, String expression) => + /// "new ${targetType.name}.fromInt($expression)"; + /// ```. + Object deserialize(DartType targetType, String expression, T context); +} + +Object commonNullPrefix( + bool nullable, + String expression, + Object unsafeExpression, +) => + nullable + ? '$expression == null ? null : $unsafeExpression' + : unsafeExpression; diff --git a/json_serializable-3.5.2/lib/src/type_helper_ctx.dart b/json_serializable-3.5.2/lib/src/type_helper_ctx.dart new file mode 100644 index 000000000..84ea35199 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helper_ctx.dart @@ -0,0 +1,161 @@ +// 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. + +import 'package:analyzer/dart/constant/value.dart'; +import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/type.dart'; +import 'package:json_annotation/json_annotation.dart'; + +import 'helper_core.dart'; +import 'type_helper.dart'; +import 'type_helpers/convert_helper.dart'; +import 'unsupported_type_error.dart'; +import 'utils.dart'; + +TypeHelperCtx typeHelperContext( + HelperCore helperCore, FieldElement fieldElement, JsonKey key) => + TypeHelperCtx._(helperCore, fieldElement, key); + +class TypeHelperCtx + implements TypeHelperContextWithConfig, TypeHelperContextWithConvert { + final HelperCore _helperCore; + final JsonKey _key; + + @override + final FieldElement fieldElement; + + @override + bool get nullable => _key.nullable; + + @override + ClassElement get classElement => _helperCore.element; + + @override + JsonSerializable get config => _helperCore.config; + + TypeHelperCtx._(this._helperCore, this.fieldElement, this._key); + + @override + ConvertData get serializeConvertData => _pairFromContext?.toJson; + + @override + ConvertData get deserializeConvertData => _pairFromContext?.fromJson; + + _ConvertPair get _pairFromContext => _ConvertPair(fieldElement); + + @override + void addMember(String memberContent) { + _helperCore.addMember(memberContent); + } + + @override + Object serialize(DartType targetType, String expression) => _run( + targetType, + expression, + (TypeHelper th) => th.serialize(targetType, expression, this), + ); + + @override + Object deserialize(DartType targetType, String expression) => _run( + targetType, + expression, + (TypeHelper th) => th.deserialize(targetType, expression, this), + ); + + Object _run( + DartType targetType, + String expression, + Object Function(TypeHelper) invoke, + ) => + _helperCore.allTypeHelpers.map(invoke).firstWhere( + (r) => r != null, + orElse: () => throw UnsupportedTypeError(targetType, expression), + ); +} + +class _ConvertPair { + static final _expando = Expando<_ConvertPair>(); + + final ConvertData fromJson, toJson; + + _ConvertPair._(this.fromJson, this.toJson); + + factory _ConvertPair(FieldElement element) { + var pair = _expando[element]; + + if (pair == null) { + final obj = jsonKeyAnnotation(element); + if (obj.isNull) { + pair = _ConvertPair._(null, null); + } else { + final toJson = _convertData(obj.objectValue, element, false); + final fromJson = _convertData(obj.objectValue, element, true); + pair = _ConvertPair._(fromJson, toJson); + } + _expando[element] = pair; + } + return pair; + } +} + +ConvertData _convertData(DartObject obj, FieldElement element, bool isFrom) { + final paramName = isFrom ? 'fromJson' : 'toJson'; + final objectValue = obj.getField(paramName); + + if (objectValue == null || objectValue.isNull) { + return null; + } + + final executableElement = objectValue.toFunctionValue(); + + if (executableElement.parameters.isEmpty || + executableElement.parameters.first.isNamed || + executableElement.parameters.where((pe) => !pe.isOptional).length > 1) { + throwUnsupported( + element, + 'The `$paramName` function `${executableElement.name}` must have one ' + 'positional parameter.'); + } + + final argType = executableElement.parameters.first.type; + if (isFrom) { + final returnType = executableElement.returnType; + + if (returnType is TypeParameterType) { + // We keep things simple in this case. We rely on inferred type arguments + // to the `fromJson` function. + // TODO: consider adding error checking here if there is confusion. + } else if (!returnType.isAssignableTo(element.type)) { + final returnTypeCode = typeToCode(returnType); + final elementTypeCode = typeToCode(element.type); + throwUnsupported( + element, + 'The `$paramName` function `${executableElement.name}` return type ' + '`$returnTypeCode` is not compatible with field type ' + '`$elementTypeCode`.'); + } + } else { + if (argType is TypeParameterType) { + // We keep things simple in this case. We rely on inferred type arguments + // to the `fromJson` function. + // TODO: consider adding error checking here if there is confusion. + } else if (!element.type.isAssignableTo(argType)) { + final argTypeCode = typeToCode(argType); + final elementTypeCode = typeToCode(element.type); + throwUnsupported( + element, + 'The `$paramName` function `${executableElement.name}` argument type ' + '`$argTypeCode` is not compatible with field type' + ' `$elementTypeCode`.'); + } + } + + var name = executableElement.name; + + if (executableElement is MethodElement) { + name = '${executableElement.enclosingElement.name}.$name'; + } + + return ConvertData(name, argType); +} diff --git a/json_serializable-3.5.2/lib/src/type_helpers/big_int_helper.dart b/json_serializable-3.5.2/lib/src/type_helpers/big_int_helper.dart new file mode 100644 index 000000000..60017827f --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/big_int_helper.dart @@ -0,0 +1,28 @@ +// 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. + +import 'package:analyzer/dart/element/type.dart'; + +import '../type_helper.dart'; +import 'to_from_string.dart'; + +class BigIntHelper extends TypeHelper { + const BigIntHelper(); + + @override + String serialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) => + bigIntString.serialize(targetType, expression, context.nullable); + + @override + String deserialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) => + bigIntString.deserialize(targetType, expression, context.nullable, false); +} diff --git a/json_serializable-3.5.2/lib/src/type_helpers/convert_helper.dart b/json_serializable-3.5.2/lib/src/type_helpers/convert_helper.dart new file mode 100644 index 000000000..10c9fc22c --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/convert_helper.dart @@ -0,0 +1,64 @@ +// 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. + +import 'package:analyzer/dart/element/type.dart'; + +import '../json_key_utils.dart'; +import '../shared_checkers.dart'; +import '../type_helper.dart'; +import '../utils.dart'; + +/// Information used by [ConvertHelper] when handling `JsonKey`-annotated +/// fields with `toJson` or `fromJson` values set. +class ConvertData { + final String name; + final DartType paramType; + + ConvertData(this.name, this.paramType); +} + +abstract class TypeHelperContextWithConvert extends TypeHelperContext { + ConvertData get serializeConvertData; + + ConvertData get deserializeConvertData; +} + +class ConvertHelper extends TypeHelper { + const ConvertHelper(); + + @override + String serialize( + DartType targetType, + String expression, + TypeHelperContextWithConvert context, + ) { + final toJsonData = context.serializeConvertData; + if (toJsonData == null) { + return null; + } + + logFieldWithConversionFunction(context.fieldElement); + + assert(toJsonData.paramType is TypeParameterType || + targetType.isAssignableTo(toJsonData.paramType)); + return '${toJsonData.name}($expression)'; + } + + @override + String deserialize( + DartType targetType, + String expression, + TypeHelperContextWithConvert context, + ) { + final fromJsonData = context.deserializeConvertData; + if (fromJsonData == null) { + return null; + } + + logFieldWithConversionFunction(context.fieldElement); + + final asContent = asStatement(fromJsonData.paramType); + return '${fromJsonData.name}($expression$asContent)'; + } +} diff --git a/json_serializable-3.5.2/lib/src/type_helpers/date_time_helper.dart b/json_serializable-3.5.2/lib/src/type_helpers/date_time_helper.dart new file mode 100644 index 000000000..e10a6f96c --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/date_time_helper.dart @@ -0,0 +1,29 @@ +// 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. + +import 'package:analyzer/dart/element/type.dart'; + +import '../type_helper.dart'; +import 'to_from_string.dart'; + +class DateTimeHelper extends TypeHelper { + const DateTimeHelper(); + + @override + String serialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) => + dateTimeString.serialize(targetType, expression, context.nullable); + + @override + String deserialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) => + dateTimeString.deserialize( + targetType, expression, context.nullable, false); +} diff --git a/json_serializable-3.5.2/lib/src/type_helpers/duration_helper.dart b/json_serializable-3.5.2/lib/src/type_helpers/duration_helper.dart new file mode 100644 index 000000000..63bdd52d7 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/duration_helper.dart @@ -0,0 +1,53 @@ +// 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. + +import 'package:analyzer/dart/element/type.dart'; +import 'package:source_gen/source_gen.dart' show TypeChecker; + +import '../type_helper.dart'; + +class DurationHelper extends TypeHelper { + const DurationHelper(); + + @override + String serialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) { + if (!_matchesType(targetType)) { + return null; + } + + final buffer = StringBuffer(expression); + + if (context.nullable) { + buffer.write('?'); + } + + buffer.write('.inMicroseconds'); + + return buffer.toString(); + } + + @override + String deserialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) { + if (!_matchesType(targetType)) { + return null; + } + + return commonNullPrefix( + context.nullable, + expression, + 'Duration(microseconds: $expression as int)', + ).toString(); + } +} + +bool _matchesType(DartType type) => + const TypeChecker.fromUrl('dart:core#Duration').isExactlyType(type); diff --git a/json_serializable-3.5.2/lib/src/type_helpers/enum_helper.dart b/json_serializable-3.5.2/lib/src/type_helpers/enum_helper.dart new file mode 100644 index 000000000..bf1128fcd --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/enum_helper.dart @@ -0,0 +1,120 @@ +// 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. + +import 'package:analyzer/dart/element/type.dart'; + +import '../json_key_utils.dart'; +import '../json_literal_generator.dart'; +import '../type_helper.dart'; +import '../utils.dart'; + +final simpleExpression = RegExp('^[a-zA-Z_]+\$'); + +class EnumHelper extends TypeHelper { + const EnumHelper(); + + @override + String serialize( + DartType targetType, + String expression, + TypeHelperContextWithConfig context, + ) { + final memberContent = _enumValueMapFromType(targetType); + + if (memberContent == null) { + return null; + } + + context.addMember(memberContent); + + return '${_constMapName(targetType)}[$expression]'; + } + + @override + String deserialize( + DartType targetType, + String expression, + TypeHelperContextWithConfig context, + ) { + final memberContent = _enumValueMapFromType(targetType); + + if (memberContent == null) { + return null; + } + + context.addMember(_enumDecodeHelper); + + if (context.nullable) { + context.addMember(_enumDecodeHelperNullable); + } + + context.addMember(memberContent); + + final functionName = + context.nullable ? r'_$enumDecodeNullable' : r'_$enumDecode'; + + final jsonKey = jsonKeyForField(context.fieldElement, context.config); + final args = [ + _constMapName(targetType), + expression, + if (jsonKey.unknownEnumValue != null) + 'unknownValue: ${jsonKey.unknownEnumValue}', + ]; + + return '$functionName(${args.join(', ')})'; + } +} + +String _constMapName(DartType targetType) => + '_\$${targetType.element.name}EnumMap'; + +String _enumValueMapFromType(DartType targetType) { + final enumMap = enumFieldsMap(targetType); + + if (enumMap == null) { + return null; + } + + final items = enumMap.entries + .map((e) => ' ${targetType.element.name}.${e.key.name}: ' + '${jsonLiteralAsDart(e.value)},') + .join(); + + return 'const ${_constMapName(targetType)} = {\n$items\n};'; +} + +const _enumDecodeHelper = r''' +T _$enumDecode( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} +'''; + +const _enumDecodeHelperNullable = r''' +T _$enumDecodeNullable( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode(enumValues, source, unknownValue: unknownValue); +}'''; diff --git a/json_serializable-3.5.2/lib/src/type_helpers/generic_factory_helper.dart b/json_serializable-3.5.2/lib/src/type_helpers/generic_factory_helper.dart new file mode 100644 index 000000000..0a3bb8aba --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/generic_factory_helper.dart @@ -0,0 +1,50 @@ +// Copyright (c) 2020, 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. + +import 'package:analyzer/dart/element/type.dart'; + +import '../lambda_result.dart'; +import '../type_helper.dart'; + +class GenericFactoryHelper extends TypeHelper { + const GenericFactoryHelper(); + + @override + Object serialize( + DartType targetType, + String expression, + TypeHelperContextWithConfig context, + ) { + if (context.config.genericArgumentFactories && + targetType is TypeParameterType) { + return LambdaResult(expression, toJsonForType(targetType)); + } + + return null; + } + + @override + Object deserialize( + DartType targetType, + String expression, + TypeHelperContextWithConfig context, + ) { + if (context.config.genericArgumentFactories && + targetType is TypeParameterType) { + return LambdaResult(expression, fromJsonForType(targetType)); + } + + return null; + } +} + +String toJsonForType(TypeParameterType type) => + toJsonForName(type.getDisplayString(withNullability: false)); + +String toJsonForName(String genericType) => 'toJson$genericType'; + +String fromJsonForType(TypeParameterType type) => + fromJsonForName(type.getDisplayString(withNullability: false)); + +String fromJsonForName(String genericType) => 'fromJson$genericType'; diff --git a/json_serializable-3.5.2/lib/src/type_helpers/iterable_helper.dart b/json_serializable-3.5.2/lib/src/type_helpers/iterable_helper.dart new file mode 100644 index 000000000..30be10767 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/iterable_helper.dart @@ -0,0 +1,102 @@ +// 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. + +import 'package:analyzer/dart/element/type.dart'; +import 'package:source_gen/source_gen.dart' show TypeChecker; + +import '../constants.dart'; +import '../lambda_result.dart'; +import '../shared_checkers.dart'; +import '../type_helper.dart'; + +class IterableHelper extends TypeHelper { + const IterableHelper(); + + @override + String serialize( + DartType targetType, + String expression, + TypeHelperContextWithConfig context, + ) { + if (!coreIterableTypeChecker.isAssignableFromType(targetType)) { + return null; + } + + final itemType = coreIterableGenericType(targetType); + + // This block will yield a regular list, which works fine for JSON + // Although it's possible that child elements may be marked unsafe + + var isList = _coreListChecker.isAssignableFromType(targetType); + final subField = context.serialize(itemType, closureArg); + + final optionalQuestion = context.nullable ? '?' : ''; + + // In the case of trivial JSON types (int, String, etc), `subField` + // will be identical to `substitute` – so no explicit mapping is needed. + // If they are not equal, then we to write out the substitution. + if (subField != closureArg) { + final lambda = LambdaResult.process(subField, closureArg); + + expression = '$expression$optionalQuestion.map($lambda)'; + + // expression now represents an Iterable (even if it started as a List + // ...resetting `isList` to `false`. + isList = false; + } + + if (!isList) { + // If the static type is not a List, generate one. + expression += '$optionalQuestion.toList()'; + } + + return expression; + } + + @override + String deserialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) { + if (!(coreIterableTypeChecker.isExactlyType(targetType) || + _coreListChecker.isExactlyType(targetType) || + _coreSetChecker.isExactlyType(targetType))) { + return null; + } + + final iterableGenericType = coreIterableGenericType(targetType); + + final itemSubVal = context.deserialize(iterableGenericType, closureArg); + + var output = '$expression as List'; + + // If `itemSubVal` is the same and it's not a Set, then we don't need to do + // anything fancy + if (closureArg == itemSubVal && + !_coreSetChecker.isExactlyType(targetType)) { + return output; + } + + output = '($output)'; + + final optionalQuestion = context.nullable ? '?' : ''; + + if (closureArg != itemSubVal) { + final lambda = LambdaResult.process(itemSubVal, closureArg); + output += '$optionalQuestion.map($lambda)'; + } + + if (_coreListChecker.isExactlyType(targetType)) { + output += '$optionalQuestion.toList()'; + } else if (_coreSetChecker.isExactlyType(targetType)) { + output += '$optionalQuestion.toSet()'; + } + + return output; + } +} + +const _coreListChecker = TypeChecker.fromUrl('dart:core#List'); +const _coreSetChecker = TypeChecker.fromUrl('dart:core#Set'); diff --git a/json_serializable-3.5.2/lib/src/type_helpers/json_converter_helper.dart b/json_serializable-3.5.2/lib/src/type_helpers/json_converter_helper.dart new file mode 100644 index 000000000..aae2dd580 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/json_converter_helper.dart @@ -0,0 +1,219 @@ +// 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. + +import 'package:analyzer/dart/constant/value.dart'; +import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/type.dart'; +import 'package:json_annotation/json_annotation.dart'; +import 'package:source_gen/source_gen.dart'; + +import '../helper_core.dart'; +import '../json_key_utils.dart'; +import '../lambda_result.dart'; +import '../shared_checkers.dart'; +import '../type_helper.dart'; + +/// A [TypeHelper] that supports classes annotated with implementations of +/// [JsonConverter]. +class JsonConverterHelper extends TypeHelper { + const JsonConverterHelper(); + + @override + Object serialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) { + final converter = _typeConverter(targetType, context); + + if (converter == null) { + return null; + } + + logFieldWithConversionFunction(context.fieldElement); + + return LambdaResult(expression, '${converter.accessString}.toJson'); + } + + @override + Object deserialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) { + final converter = _typeConverter(targetType, context); + if (converter == null) { + return null; + } + + final asContent = asStatement(converter.jsonType); + + logFieldWithConversionFunction(context.fieldElement); + + return LambdaResult( + '$expression$asContent', '${converter.accessString}.fromJson'); + } +} + +class _JsonConvertData { + final String accessString; + final DartType jsonType; + + _JsonConvertData.className( + String className, + String accessor, + this.jsonType, + ) : accessString = 'const $className${_withAccessor(accessor)}()'; + + _JsonConvertData.genericClass( + String className, + String genericTypeArg, + String accessor, + this.jsonType, + ) : accessString = '$className<$genericTypeArg>${_withAccessor(accessor)}()'; + + _JsonConvertData.propertyAccess(this.accessString, this.jsonType); + + static String _withAccessor(String accessor) => + accessor.isEmpty ? '' : '.$accessor'; +} + +_JsonConvertData _typeConverter(DartType targetType, TypeHelperContext ctx) { + List<_ConverterMatch> converterMatches(List items) => items + .map((annotation) => _compatibleMatch(targetType, annotation)) + .where((dt) => dt != null) + .toList(); + + var matchingAnnotations = converterMatches(ctx.fieldElement.metadata); + + if (matchingAnnotations.isEmpty) { + matchingAnnotations = + converterMatches(ctx.fieldElement.getter?.metadata ?? []); + + if (matchingAnnotations.isEmpty) { + matchingAnnotations = converterMatches(ctx.classElement.metadata); + } + } + + return _typeConverterFrom(matchingAnnotations, targetType); +} + +_JsonConvertData _typeConverterFrom( + List<_ConverterMatch> matchingAnnotations, + DartType targetType, +) { + if (matchingAnnotations.isEmpty) { + return null; + } + + if (matchingAnnotations.length > 1) { + final targetTypeCode = typeToCode(targetType); + throw InvalidGenerationSourceError( + 'Found more than one matching converter for `$targetTypeCode`.', + element: matchingAnnotations[1].elementAnnotation.element); + } + + final match = matchingAnnotations.single; + + final annotationElement = match.elementAnnotation.element; + if (annotationElement is PropertyAccessorElement) { + final enclosing = annotationElement.enclosingElement; + + var accessString = annotationElement.name; + + if (enclosing is ClassElement) { + accessString = '${enclosing.name}.$accessString'; + } + + return _JsonConvertData.propertyAccess(accessString, match.jsonType); + } + + final reviver = ConstantReader(match.annotation).revive(); + + if (reviver.namedArguments.isNotEmpty || + reviver.positionalArguments.isNotEmpty) { + throw InvalidGenerationSourceError( + 'Generators with constructor arguments are not supported.', + element: match.elementAnnotation.element); + } + + if (match.genericTypeArg != null) { + return _JsonConvertData.genericClass( + match.annotation.type.element.name, + match.genericTypeArg, + reviver.accessor, + match.jsonType, + ); + } + + return _JsonConvertData.className( + match.annotation.type.element.name, + reviver.accessor, + match.jsonType, + ); +} + +class _ConverterMatch { + final DartObject annotation; + final DartType jsonType; + final ElementAnnotation elementAnnotation; + final String genericTypeArg; + + _ConverterMatch( + this.elementAnnotation, + this.annotation, + this.jsonType, + this.genericTypeArg, + ); +} + +_ConverterMatch _compatibleMatch( + DartType targetType, + ElementAnnotation annotation, +) { + final constantValue = annotation.computeConstantValue(); + + final converterClassElement = constantValue.type.element as ClassElement; + + final jsonConverterSuper = converterClassElement.allSupertypes.singleWhere( + (e) => e is InterfaceType && _jsonConverterChecker.isExactly(e.element), + orElse: () => null); + + if (jsonConverterSuper == null) { + return null; + } + + assert(jsonConverterSuper.element.typeParameters.length == 2); + assert(jsonConverterSuper.typeArguments.length == 2); + + final fieldType = jsonConverterSuper.typeArguments[0]; + + if (fieldType == targetType) { + return _ConverterMatch( + annotation, constantValue, jsonConverterSuper.typeArguments[1], null); + } + + if (fieldType is TypeParameterType && targetType is TypeParameterType) { + assert(annotation.element is! PropertyAccessorElement); + assert(converterClassElement.typeParameters.isNotEmpty); + if (converterClassElement.typeParameters.length > 1) { + throw InvalidGenerationSourceError( + '`JsonConverter` implementations can have no more than one type ' + 'argument. `${converterClassElement.name}` has ' + '${converterClassElement.typeParameters.length}.', + element: converterClassElement); + } + + return _ConverterMatch( + annotation, + constantValue, + jsonConverterSuper.typeArguments[1], + targetType.element.name, + ); + } + + return null; +} + +const _jsonConverterChecker = TypeChecker.fromRuntime(JsonConverter); diff --git a/json_serializable-3.5.2/lib/src/type_helpers/json_helper.dart b/json_serializable-3.5.2/lib/src/type_helpers/json_helper.dart new file mode 100644 index 000000000..b783e19f3 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/json_helper.dart @@ -0,0 +1,284 @@ +// 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. + +import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/nullability_suffix.dart'; +import 'package:analyzer/dart/element/type.dart'; +import 'package:json_annotation/json_annotation.dart'; +import 'package:source_gen/source_gen.dart'; + +import '../shared_checkers.dart'; +import '../type_helper.dart'; +import '../utils.dart'; +import 'generic_factory_helper.dart'; + +const _helperLambdaParam = 'value'; + +class JsonHelper extends TypeHelper { + const JsonHelper(); + + /// Simply returns the [expression] provided. + /// + /// By default, JSON encoding in from `dart:convert` calls `toJson()` on + /// provided objects. + @override + String serialize( + DartType targetType, + String expression, + TypeHelperContextWithConfig context, + ) { + if (!_canSerialize(context.config, targetType)) { + return null; + } + + final interfaceType = targetType as InterfaceType; + + final toJsonArgs = []; + + var toJson = _toJsonMethod(interfaceType); + + if (toJson != null) { + // Using the `declaration` here so we get the original definition – + // and not one with the generics already populated. + toJson = toJson.declaration; + + toJsonArgs.addAll( + _helperParams( + context.serialize, + _encodeHelper, + interfaceType, + toJson.parameters.where((element) => element.isRequiredPositional), + toJson, + ), + ); + } + + if (context.config.explicitToJson || toJsonArgs.isNotEmpty) { + return '$expression${context.nullable ? '?' : ''}' + '.toJson(${toJsonArgs.map((a) => '$a, ').join()} )'; + } + return expression; + } + + @override + String deserialize( + DartType targetType, + String expression, + TypeHelperContextWithConfig context, + ) { + if (targetType is! InterfaceType) { + return null; + } + + final type = targetType as InterfaceType; + final classElement = type.element; + + final fromJsonCtor = classElement.constructors + .singleWhere((ce) => ce.name == 'fromJson', orElse: () => null); + + var output = expression; + if (fromJsonCtor != null) { + final positionalParams = fromJsonCtor.parameters + .where((element) => element.isPositional) + .toList(); + + if (positionalParams.isEmpty) { + throw InvalidGenerationSourceError( + 'Expecting a `fromJson` constructor with exactly one positional ' + 'parameter. Found a constructor with 0 parameters.', + element: fromJsonCtor, + ); + } + + var asCastType = positionalParams.first.type; + + if (asCastType is InterfaceType) { + final instantiated = _instantiate(asCastType as InterfaceType, type); + if (instantiated != null) { + asCastType = instantiated; + } + } + + output = context.deserialize(asCastType, output).toString(); + + final args = [ + output, + ..._helperParams( + context.deserialize, + _decodeHelper, + targetType as InterfaceType, + positionalParams.skip(1), + fromJsonCtor, + ), + ]; + + output = args.join(', '); + } else if (_annotation(context.config, type)?.createFactory == true) { + if (context.config.anyMap) { + output += ' as Map'; + } else { + output += ' as Map'; + } + } else { + return null; + } + + // TODO: the type could be imported from a library with a prefix! + // https://github.com/google/json_serializable.dart/issues/19 + output = '${targetType.element.name}.fromJson($output)'; + + return commonNullPrefix(context.nullable, expression, output).toString(); + } +} + +List _helperParams( + Object Function(DartType, String) execute, + TypeParameterType Function(ParameterElement, Element) paramMapper, + InterfaceType type, + Iterable positionalParams, + Element targetElement, +) { + final rest = []; + for (var param in positionalParams) { + rest.add(paramMapper(param, targetElement)); + } + + final args = []; + + for (var helperArg in rest) { + final typeParamIndex = + type.element.typeParameters.indexOf(helperArg.element); + + // TODO: throw here if `typeParamIndex` is -1 ? + final typeArg = type.typeArguments[typeParamIndex]; + final body = execute(typeArg, _helperLambdaParam); + args.add('($_helperLambdaParam) => $body'); + } + + return args; +} + +TypeParameterType _decodeHelper( + ParameterElement param, + Element targetElement, +) { + final type = param.type; + + if (type is FunctionType && + type.returnType is TypeParameterType && + type.normalParameterTypes.length == 1) { + final funcReturnType = type.returnType; + + if (param.name == fromJsonForName(funcReturnType.element.name)) { + final funcParamType = type.normalParameterTypes.single; + + if (funcParamType.isDartCoreObject || funcParamType.isDynamic) { + return funcReturnType as TypeParameterType; + } + } + } + + throw InvalidGenerationSourceError( + 'Expecting a `fromJson` constructor with exactly one positional ' + 'parameter. ' + 'The only extra parameters allowed are functions of the form ' + '`T Function(Object) ${fromJsonForName('T')}` where `T` is a type ' + 'parameter of the target type.', + element: targetElement, + ); +} + +TypeParameterType _encodeHelper( + ParameterElement param, + Element targetElement, +) { + final type = param.type; + + if (type is FunctionType && + isObjectOrDynamic(type.returnType) && + type.normalParameterTypes.length == 1) { + final funcParamType = type.normalParameterTypes.single; + + if (param.name == toJsonForName(funcParamType.element.name)) { + if (funcParamType is TypeParameterType) { + return funcParamType; + } + } + } + + throw InvalidGenerationSourceError( + 'Expecting a `toJson` function with no required parameters. ' + 'The only extra parameters allowed are functions of the form ' + '`Object Function(T) toJsonT` where `T` is a type parameter of the target ' + ' type.', + element: targetElement, + ); +} + +bool _canSerialize(JsonSerializable config, DartType type) { + if (type is InterfaceType) { + final toJsonMethod = _toJsonMethod(type); + + if (toJsonMethod != null) { + return true; + } + + if (_annotation(config, type)?.createToJson == true) { + // TODO: consider logging that we're assuming a user will wire up the + // generated mixin at some point... + return true; + } + } + return false; +} + +/// Returns an instantiation of [ctorParamType] by providing argument types +/// derived by matching corresponding type parameters from [classType]. +InterfaceType _instantiate( + InterfaceType ctorParamType, + InterfaceType classType, +) { + final argTypes = ctorParamType.typeArguments.map((arg) { + final typeParamIndex = classType.element.typeParameters.indexWhere( + // TODO: not 100% sure `nullabilitySuffix` is right + (e) => e.instantiate(nullabilitySuffix: arg.nullabilitySuffix) == arg); + if (typeParamIndex >= 0) { + return classType.typeArguments[typeParamIndex]; + } else { + // TODO: perhaps throw UnsupportedTypeError? + return null; + } + }).toList(); + + if (argTypes.any((e) => e == null)) { + // TODO: perhaps throw UnsupportedTypeError? + return null; + } + + return ctorParamType.element.instantiate( + typeArguments: argTypes, + // TODO: not 100% sure nullabilitySuffix is right... Works for now + nullabilitySuffix: NullabilitySuffix.none, + ); +} + +JsonSerializable _annotation(JsonSerializable config, InterfaceType source) { + final annotations = const TypeChecker.fromRuntime(JsonSerializable) + .annotationsOfExact(source.element, throwOnUnresolved: false) + .toList(); + + if (annotations.isEmpty) { + return null; + } + + return mergeConfig( + config, + ConstantReader(annotations.single), + classElement: source.element, + ); +} + +MethodElement _toJsonMethod(DartType type) => typeImplementations(type) + .map((dt) => dt is InterfaceType ? dt.getMethod('toJson') : null) + .firstWhere((me) => me != null, orElse: () => null); diff --git a/json_serializable-3.5.2/lib/src/type_helpers/map_helper.dart b/json_serializable-3.5.2/lib/src/type_helpers/map_helper.dart new file mode 100644 index 000000000..09c8219c3 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/map_helper.dart @@ -0,0 +1,167 @@ +// 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. + +import 'package:analyzer/dart/element/type.dart'; + +import '../constants.dart'; +import '../shared_checkers.dart'; +import '../type_helper.dart'; +import '../unsupported_type_error.dart'; +import '../utils.dart'; +import 'to_from_string.dart'; + +const _keyParam = 'k'; + +class MapHelper extends TypeHelper { + const MapHelper(); + + @override + String serialize( + DartType targetType, + String expression, + TypeHelperContextWithConfig context, + ) { + if (!coreMapTypeChecker.isAssignableFromType(targetType)) { + return null; + } + final args = typeArgumentsOf(targetType, coreMapTypeChecker); + assert(args.length == 2); + + final keyType = args[0]; + final valueType = args[1]; + + _checkSafeKeyType(expression, keyType); + + final subFieldValue = context.serialize(valueType, closureArg); + final subKeyValue = + _forType(keyType)?.serialize(keyType, _keyParam, false) ?? + context.serialize(keyType, _keyParam); + + if (closureArg == subFieldValue && _keyParam == subKeyValue) { + return expression; + } + + final optionalQuestion = context.nullable ? '?' : ''; + + return '$expression$optionalQuestion' + '.map(($_keyParam, $closureArg) => ' + 'MapEntry($subKeyValue, $subFieldValue))'; + } + + @override + String deserialize( + DartType targetType, + String expression, + TypeHelperContextWithConfig context, + ) { + if (!coreMapTypeChecker.isExactlyType(targetType)) { + return null; + } + + final typeArgs = typeArgumentsOf(targetType, coreMapTypeChecker); + assert(typeArgs.length == 2); + final keyArg = typeArgs.first; + final valueArg = typeArgs.last; + + _checkSafeKeyType(expression, keyArg); + + final valueArgIsAny = isObjectOrDynamic(valueArg); + final isKeyStringable = _isKeyStringable(keyArg); + + if (!isKeyStringable) { + if (valueArgIsAny) { + if (context.config.anyMap) { + if (isObjectOrDynamic(keyArg)) { + return '$expression as Map'; + } + } else { + // this is the trivial case. Do a runtime cast to the known type of + // JSON map values - `Map` + return '$expression as Map'; + } + } + + if (!context.nullable && + (valueArgIsAny || + simpleJsonTypeChecker.isAssignableFromType(valueArg))) { + // No mapping of the values or null check required! + final valueString = valueArg.getDisplayString(withNullability: false); + return 'Map.from($expression as Map)'; + } + } + + // In this case, we're going to create a new Map with matching reified + // types. + + final itemSubVal = context.deserialize(valueArg, closureArg); + + final optionalQuestion = context.nullable ? '?' : ''; + + final mapCast = + context.config.anyMap ? 'as Map' : 'as Map'; + + String keyUsage; + if (isEnum(keyArg)) { + keyUsage = context.deserialize(keyArg, _keyParam).toString(); + } else if (context.config.anyMap && !isObjectOrDynamic(keyArg)) { + keyUsage = '$_keyParam as String'; + } else { + keyUsage = _keyParam; + } + + final toFromString = _forType(keyArg); + if (toFromString != null) { + keyUsage = toFromString.deserialize(keyArg, keyUsage, false, true); + } + + return '($expression $mapCast)$optionalQuestion.map( ' + '($_keyParam, $closureArg) => MapEntry($keyUsage, $itemSubVal),)'; + } +} + +final _intString = ToFromStringHelper('int.parse', 'toString()', 'int'); + +/// [ToFromStringHelper] instances representing non-String types that can +/// be used as [Map] keys. +final _instances = [ + bigIntString, + dateTimeString, + _intString, + uriString, +]; + +ToFromStringHelper _forType(DartType type) => + _instances.singleWhere((i) => i.matches(type), orElse: () => null); + +/// Returns `true` if [keyType] can be automatically converted to/from String – +/// and is therefor usable as a key in a [Map]. +bool _isKeyStringable(DartType keyType) => + isEnum(keyType) || _instances.any((inst) => inst.matches(keyType)); + +void _checkSafeKeyType(String expression, DartType keyArg) { + // We're not going to handle converting key types at the moment + // So the only safe types for key are dynamic/Object/String/enum + if (isObjectOrDynamic(keyArg) || + coreStringTypeChecker.isExactlyType(keyArg) || + _isKeyStringable(keyArg)) { + return; + } + + throw UnsupportedTypeError( + keyArg, + expression, + 'Map keys must be one of: ${_allowedTypeNames.join(', ')}.', + ); +} + +/// The names of types that can be used as [Map] keys. +/// +/// Used in [_checkSafeKeyType] to provide a helpful error with unsupported +/// types. +Iterable get _allowedTypeNames => const [ + 'Object', + 'dynamic', + 'enum', + 'String', + ].followedBy(_instances.map((i) => i.coreTypeName)); diff --git a/json_serializable-3.5.2/lib/src/type_helpers/to_from_string.dart b/json_serializable-3.5.2/lib/src/type_helpers/to_from_string.dart new file mode 100644 index 000000000..7a5d94715 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/to_from_string.dart @@ -0,0 +1,82 @@ +// Copyright (c) 2019, 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. + +import 'package:analyzer/dart/element/type.dart'; +import 'package:source_gen/source_gen.dart'; + +import '../type_helper.dart'; + +final bigIntString = ToFromStringHelper( + 'BigInt.parse', + 'toString()', + 'BigInt', +); + +final dateTimeString = ToFromStringHelper( + 'DateTime.parse', + 'toIso8601String()', + 'DateTime', +); + +final uriString = ToFromStringHelper( + 'Uri.parse', + 'toString()', + 'Uri', +); + +/// Package-internal helper that unifies implementations of [Type]s that convert +/// trivially to-from [String]. +class ToFromStringHelper { + /// The function or constructor to call when creating the associated type. + /// + /// Assumed to have one parameter of type [String]. + /// + /// Example: `MyClass.parse` + final String _parse; + + /// Represents an invocation – property access or function call – on an + /// instance of the target type that returns [String]. + /// + /// Examples: `toString()` for a function or `stringValue` for a property. + final String _toString; + final String coreTypeName; + final TypeChecker _checker; + + ToFromStringHelper(this._parse, this._toString, this.coreTypeName) + : _checker = TypeChecker.fromUrl('dart:core#$coreTypeName'); + + bool matches(DartType type) => _checker.isExactlyType(type); + + String serialize( + DartType type, + String expression, + bool nullable, + ) { + if (!matches(type)) { + return null; + } + + if (nullable) { + expression = '$expression?'; + } + + return '$expression.$_toString'; + } + + String deserialize( + DartType type, + String expression, + bool nullable, + bool isString, + ) { + if (!matches(type)) { + return null; + } + + final parseParam = isString ? expression : '$expression as String'; + + return commonNullPrefix(nullable, expression, '$_parse($parseParam)') + .toString(); + } +} diff --git a/json_serializable-3.5.2/lib/src/type_helpers/uri_helper.dart b/json_serializable-3.5.2/lib/src/type_helpers/uri_helper.dart new file mode 100644 index 000000000..81267d903 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/uri_helper.dart @@ -0,0 +1,28 @@ +// 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. + +import 'package:analyzer/dart/element/type.dart'; + +import '../type_helper.dart'; +import 'to_from_string.dart'; + +class UriHelper extends TypeHelper { + const UriHelper(); + + @override + String serialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) => + uriString.serialize(targetType, expression, context.nullable); + + @override + String deserialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) => + uriString.deserialize(targetType, expression, context.nullable, false); +} diff --git a/json_serializable-3.5.2/lib/src/type_helpers/value_helper.dart b/json_serializable-3.5.2/lib/src/type_helpers/value_helper.dart new file mode 100644 index 000000000..ef898e0a4 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/type_helpers/value_helper.dart @@ -0,0 +1,48 @@ +// 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. + +import 'package:analyzer/dart/element/type.dart'; +import 'package:source_gen/source_gen.dart' show TypeChecker; + +import '../helper_core.dart'; +import '../shared_checkers.dart'; +import '../type_helper.dart'; + +class ValueHelper extends TypeHelper { + const ValueHelper(); + + @override + String serialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) { + if (isObjectOrDynamic(targetType) || + simpleJsonTypeChecker.isAssignableFromType(targetType)) { + return expression; + } + + return null; + } + + @override + String deserialize( + DartType targetType, + String expression, + TypeHelperContext context, + ) { + if (isObjectOrDynamic(targetType)) { + // just return it as-is. We'll hope it's safe. + return expression; + } else if (const TypeChecker.fromUrl('dart:core#double') + .isExactlyType(targetType)) { + return '($expression as num)${context.nullable ? '?' : ''}.toDouble()'; + } else if (simpleJsonTypeChecker.isAssignableFromType(targetType)) { + final typeCode = typeToCode(targetType); + return '$expression as $typeCode'; + } + + return null; + } +} diff --git a/json_serializable-3.5.2/lib/src/unsupported_type_error.dart b/json_serializable-3.5.2/lib/src/unsupported_type_error.dart new file mode 100644 index 000000000..3642cc2c4 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/unsupported_type_error.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2019, 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. + +import 'package:analyzer/dart/element/type.dart'; + +/// Error thrown when code generation fails due to [type] being unsupported for +/// [reason]. +class UnsupportedTypeError extends Error { + final DartType type; + final String reason; + + /// Not currently accesses. Will likely be removed in a future release. + final String expression; + + UnsupportedTypeError(this.type, this.expression, [this.reason]); +} diff --git a/json_serializable-3.5.2/lib/src/utils.dart b/json_serializable-3.5.2/lib/src/utils.dart new file mode 100644 index 000000000..a353a8c20 --- /dev/null +++ b/json_serializable-3.5.2/lib/src/utils.dart @@ -0,0 +1,273 @@ +// Copyright (c) 2017, 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. + +import 'package:analyzer/dart/constant/value.dart'; +import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/type.dart'; +import 'package:json_annotation/json_annotation.dart'; +import 'package:meta/meta.dart' show alwaysThrows, required; +import 'package:source_gen/source_gen.dart'; + +import 'helper_core.dart'; + +const _jsonKeyChecker = TypeChecker.fromRuntime(JsonKey); + +DartObject _jsonKeyAnnotation(FieldElement element) => + _jsonKeyChecker.firstAnnotationOf(element) ?? + (element.getter == null + ? null + : _jsonKeyChecker.firstAnnotationOf(element.getter)); + +ConstantReader jsonKeyAnnotation(FieldElement element) => + ConstantReader(_jsonKeyAnnotation(element)); + +/// Returns `true` if [element] is annotated with [JsonKey]. +bool hasJsonKeyAnnotation(FieldElement element) => + _jsonKeyAnnotation(element) != null; + +final _upperCase = RegExp('[A-Z]'); + +String kebabCase(String input) => _fixCase(input, '-'); + +String snakeCase(String input) => _fixCase(input, '_'); + +String pascalCase(String input) { + if (input.isEmpty) { + return ''; + } + + return input[0].toUpperCase() + input.substring(1); +} + +String _fixCase(String input, String separator) => + input.replaceAllMapped(_upperCase, (match) { + var lower = match.group(0).toLowerCase(); + + if (match.start > 0) { + lower = '$separator$lower'; + } + + return lower; + }); + +@alwaysThrows +void throwUnsupported(FieldElement element, String message) => + throw InvalidGenerationSourceError( + 'Error with `@JsonKey` on `${element.name}`. $message', + element: element); + +FieldRename _fromDartObject(ConstantReader reader) => reader.isNull + ? null + : enumValueForDartObject( + reader.objectValue, + FieldRename.values, + (f) => f.toString().split('.')[1], + ); + +T enumValueForDartObject( + DartObject source, + List items, + String Function(T) name, +) => + items.singleWhere((v) => source.getField(name(v)) != null); + +/// Return an instance of [JsonSerializable] corresponding to a the provided +/// [reader]. +JsonSerializable _valueForAnnotation(ConstantReader reader) => JsonSerializable( + anyMap: reader.read('anyMap').literalValue as bool, + checked: reader.read('checked').literalValue as bool, + createFactory: reader.read('createFactory').literalValue as bool, + createToJson: reader.read('createToJson').literalValue as bool, + disallowUnrecognizedKeys: + reader.read('disallowUnrecognizedKeys').literalValue as bool, + explicitToJson: reader.read('explicitToJson').literalValue as bool, + fieldRename: _fromDartObject(reader.read('fieldRename')), + genericArgumentFactories: + reader.read('genericArgumentFactories').literalValue as bool, + ignoreUnannotated: reader.read('ignoreUnannotated').literalValue as bool, + includeIfNull: reader.read('includeIfNull').literalValue as bool, + nullable: reader.read('nullable').literalValue as bool, + ); + +/// Returns a [JsonSerializable] with values from the [JsonSerializable] +/// instance represented by [reader]. +/// +/// For fields that are not defined in [JsonSerializable] or `null` in [reader], +/// use the values in [config]. +/// +/// Note: if [JsonSerializable.genericArgumentFactories] is `false` for [reader] +/// and `true` for [config], the corresponding field in the return value will +/// only be `true` if [classElement] has type parameters. +JsonSerializable mergeConfig( + JsonSerializable config, + ConstantReader reader, { + @required ClassElement classElement, +}) { + final annotation = _valueForAnnotation(reader); + + return JsonSerializable( + anyMap: annotation.anyMap ?? config.anyMap, + checked: annotation.checked ?? config.checked, + createFactory: annotation.createFactory ?? config.createFactory, + createToJson: annotation.createToJson ?? config.createToJson, + disallowUnrecognizedKeys: + annotation.disallowUnrecognizedKeys ?? config.disallowUnrecognizedKeys, + explicitToJson: annotation.explicitToJson ?? config.explicitToJson, + fieldRename: annotation.fieldRename ?? config.fieldRename, + genericArgumentFactories: annotation.genericArgumentFactories ?? + (classElement.typeParameters.isNotEmpty && + config.genericArgumentFactories), + ignoreUnannotated: annotation.ignoreUnannotated ?? config.ignoreUnannotated, + includeIfNull: annotation.includeIfNull ?? config.includeIfNull, + nullable: annotation.nullable ?? config.nullable, + ); +} + +bool isEnum(DartType targetType) => + targetType is InterfaceType && targetType.element.isEnum; + +final _enumMapExpando = Expando>(); + +/// If [targetType] is an enum, returns a [Map] of the [FieldElement] instances +/// associated with the enum values mapped to the [String] values that represent +/// the serialized output. +/// +/// By default, the [String] value is just the name of the enum value. +/// If the enum value is annotated with [JsonKey], then the `name` property is +/// used if it's set and not `null`. +/// +/// If [targetType] is not an enum, `null` is returned. +Map enumFieldsMap(DartType targetType) { + MapEntry _generateEntry(FieldElement fe) { + final annotation = + const TypeChecker.fromRuntime(JsonValue).firstAnnotationOfExact(fe); + + dynamic fieldValue; + if (annotation == null) { + fieldValue = fe.name; + } else { + final reader = ConstantReader(annotation); + + final valueReader = reader.read('value'); + + if (valueReader.isString || valueReader.isNull || valueReader.isInt) { + fieldValue = valueReader.literalValue; + } else { + final targetTypeCode = typeToCode(targetType); + throw InvalidGenerationSourceError( + 'The `JsonValue` annotation on `$targetTypeCode.${fe.name}` does ' + 'not have a value of type String, int, or null.', + element: fe); + } + } + + final entry = MapEntry(fe, fieldValue); + + return entry; + } + + if (targetType is InterfaceType && targetType.element.isEnum) { + return _enumMapExpando[targetType] ??= + Map.fromEntries(targetType.element.fields + .where((p) => !p.isSynthetic) + .map(_generateEntry)); + } + return null; +} + +/// If [targetType] is an enum, returns the [FieldElement] instances associated +/// with its values. +/// +/// Otherwise, `null`. +Iterable iterateEnumFields(DartType targetType) => + enumFieldsMap(targetType)?.keys; + +/// Returns a quoted String literal for [value] that can be used in generated +/// Dart code. +String escapeDartString(String value) { + var hasSingleQuote = false; + var hasDoubleQuote = false; + var hasDollar = false; + var canBeRaw = true; + + value = value.replaceAllMapped(_escapeRegExp, (match) { + final value = match[0]; + if (value == "'") { + hasSingleQuote = true; + return value; + } else if (value == '"') { + hasDoubleQuote = true; + return value; + } else if (value == r'$') { + hasDollar = true; + return value; + } + + canBeRaw = false; + return _escapeMap[value] ?? _getHexLiteral(value); + }); + + if (!hasDollar) { + if (hasSingleQuote) { + if (!hasDoubleQuote) { + return '"$value"'; + } + // something + } else { + // trivial! + return "'$value'"; + } + } + + if (hasDollar && canBeRaw) { + if (hasSingleQuote) { + if (!hasDoubleQuote) { + // quote it with single quotes! + return 'r"$value"'; + } + } else { + // quote it with single quotes! + return "r'$value'"; + } + } + + // The only safe way to wrap the content is to escape all of the + // problematic characters - `$`, `'`, and `"` + final string = value.replaceAll(_dollarQuoteRegexp, r'\'); + return "'$string'"; +} + +final _dollarQuoteRegexp = RegExp(r"""(?=[$'"])"""); + +/// A [Map] between whitespace characters & `\` and their escape sequences. +const _escapeMap = { + '\b': r'\b', // 08 - backspace + '\t': r'\t', // 09 - tab + '\n': r'\n', // 0A - new line + '\v': r'\v', // 0B - vertical tab + '\f': r'\f', // 0C - form feed + '\r': r'\r', // 0D - carriage return + '\x7F': r'\x7F', // delete + r'\': r'\\' // backslash +}; + +final _escapeMapRegexp = _escapeMap.keys.map(_getHexLiteral).join(); + +/// A [RegExp] that matches whitespace characters that should be escaped and +/// single-quote, double-quote, and `$` +final _escapeRegExp = RegExp('[\$\'"\\x00-\\x07\\x0E-\\x1F$_escapeMapRegexp]'); + +/// Given single-character string, return the hex-escaped equivalent. +String _getHexLiteral(String input) { + final rune = input.runes.single; + final value = rune.toRadixString(16).toUpperCase().padLeft(2, '0'); + return '\\x$value'; +} + +extension DartTypeExtension on DartType { + bool isAssignableTo(DartType other) => + // If the library is `null`, treat it like dynamic => `true` + element.library == null || + element.library.typeSystem.isAssignableTo(this, other); +} diff --git a/json_serializable-3.5.2/lib/type_helper.dart b/json_serializable-3.5.2/lib/type_helper.dart new file mode 100644 index 000000000..6d574f4b5 --- /dev/null +++ b/json_serializable-3.5.2/lib/type_helper.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2017, 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. + +export 'src/shared_checkers.dart' show simpleJsonTypeChecker, typeArgumentsOf; +export 'src/type_helper.dart' + show TypeHelperContext, TypeHelperContextWithConfig, TypeHelper; +export 'src/type_helpers/big_int_helper.dart'; +export 'src/type_helpers/convert_helper.dart'; +export 'src/type_helpers/date_time_helper.dart'; +export 'src/type_helpers/duration_helper.dart'; +export 'src/type_helpers/enum_helper.dart'; +export 'src/type_helpers/iterable_helper.dart'; +export 'src/type_helpers/json_converter_helper.dart'; +export 'src/type_helpers/json_helper.dart'; +export 'src/type_helpers/map_helper.dart'; +export 'src/type_helpers/uri_helper.dart'; +export 'src/type_helpers/value_helper.dart'; +export 'src/unsupported_type_error.dart'; diff --git a/json_serializable-3.5.2/mono_pkg.yaml b/json_serializable-3.5.2/mono_pkg.yaml new file mode 100644 index 000000000..bb460725b --- /dev/null +++ b/json_serializable-3.5.2/mono_pkg.yaml @@ -0,0 +1,23 @@ +# See https://github.com/google/mono_repo.dart for details on this file +dart: +- 2.13.4 +- stable + +stages: +- analyzer_and_format: + - group: + - analyze: --fatal-warnings . + dart: [stable] + - group: + - format + - analyze: --fatal-warnings . + dart: [2.13.4] +- unit_test: + - test + - test: -p chrome +- ensure_build: + - test: --run-skipped -t presubmit-only test/ensure_build_test.dart + +cache: + directories: + - .dart_tool/build diff --git a/json_serializable-3.5.2/pubspec.yaml b/json_serializable-3.5.2/pubspec.yaml new file mode 100644 index 000000000..14ad6fb72 --- /dev/null +++ b/json_serializable-3.5.2/pubspec.yaml @@ -0,0 +1,37 @@ +name: json_serializable_3_5_2 +version: 3.5.2 +description: >- + Automatically generate code for converting to and from JSON by annotating + Dart classes. +repository: https://github.com/google/json_serializable.dart +environment: + sdk: '>=2.11.99 <3.0.0' + +dependencies: + analyzer: '>=0.39.0 <2.0.0' + build: '>=0.12.6 <3.0.0' + build_config: '>=0.2.6 <2.0.0' + + # Use a tight version constraint to ensure that a constraint on + # `json_annotation` properly constrains all features it provides. + # For v3 only – allow a wide range since the only change was to REMOVE things + # from json_annotation + json_annotation_3_1_1: + hosted: + name: json_annotation_3_1_1 + url: https://pub.workiva.org + version: ^5.3.0 # This version doesn't matter, there's only the 3_1_1 forked version + meta: ^1.1.0 + path: ^1.3.2 + source_gen: ^0.9.6 + +dev_dependencies: + build_runner: ^1.0.0 + build_verify: ^2.0.0 + collection: ^1.14.0 + dart_style: ^1.0.0 + logging: ^1.0.0 + pub_semver: ^2.0.0 + source_gen_test: ^0.1.0 + test: ^1.6.0 + yaml: ^3.0.0 diff --git a/json_serializable-3.5.2/test/config_test.dart b/json_serializable-3.5.2/test/config_test.dart new file mode 100644 index 000000000..da4959572 --- /dev/null +++ b/json_serializable-3.5.2/test/config_test.dart @@ -0,0 +1,146 @@ +// 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. + +@TestOn('vm') +import 'dart:io'; + +import 'package:build/build.dart'; +import 'package:json_annotation/json_annotation.dart'; +import 'package:json_serializable/builder.dart'; +import 'package:json_serializable/src/json_serializable_generator.dart'; +import 'package:test/test.dart'; +import 'package:yaml/yaml.dart'; + +import 'shared_config.dart'; + +void main() { + test('fields in JsonSerializable are sorted', () { + expect(generatorConfigDefaultJson.keys, + orderedEquals(generatorConfigDefaultJson.keys.toList()..sort())); + }); + + test('empty', () async { + final builder = jsonSerializable(BuilderOptions.empty); + expect(builder, isNotNull); + }); + + test('valid default config', () async { + final builder = + jsonSerializable(BuilderOptions(generatorConfigDefaultJson)); + expect(builder, isNotNull); + }); + + test('valid, non-default config', () { + expect(generatorConfigNonDefaultJson.keys, + unorderedEquals(generatorConfigDefaultJson.keys)); + + for (var entry in generatorConfigDefaultJson.entries) { + expect(generatorConfigNonDefaultJson, + containsPair(entry.key, isNot(entry.value)), + reason: 'should have values that are different than the defaults'); + } + + final builder = + jsonSerializable(BuilderOptions(generatorConfigNonDefaultJson)); + expect(builder, isNotNull); + }); + + test('config is null-protected when passed to JsonSerializableGenerator', () { + final nullValueMap = Map.fromEntries( + generatorConfigDefaultJson.entries.map((e) => MapEntry(e.key, null))); + final config = JsonSerializable.fromJson(nullValueMap); + final generator = JsonSerializableGenerator(config: config); + expect(generator.config.toJson(), generatorConfigDefaultJson); + }); + + test('readme config', () async { + final configExampleContent = File('README.md') + .readAsLinesSync() + .skipWhile((line) => line != '```yaml') + .skip(1) + .takeWhile((line) => line != '```') + .join('\n'); + + var yaml = loadYaml(configExampleContent) as YamlMap; + + for (final key in [ + 'targets', + r'$default', + 'builders', + 'json_serializable', + 'options' + ]) { + yaml = yaml[key] as YamlMap; + } + + final configMap = Map.from(yaml); + + expect(configMap.keys, unorderedEquals(generatorConfigDefaultJson.keys), + reason: 'All supported keys are documented.'); + + expect( + JsonSerializable.fromJson(configMap).toJson(), + generatorConfigDefaultJson, + ); + + final builder = jsonSerializable(BuilderOptions(configMap)); + expect(builder, isNotNull); + }); + + test('unsupported configuration', () async { + final matcher = isA().having( + (v) => v.message, + 'message', + 'Could not parse the options provided for `json_serializable`.\n' + 'Unrecognized keys: [unsupported]; ' + 'supported keys: [${_invalidConfig.keys.join(', ')}]', + ); + + expect( + () => jsonSerializable(const BuilderOptions({'unsupported': 'config'})), + throwsA(matcher)); + }); + + group('invalid config', () { + test('validated for all supported keys', () { + expect(_invalidConfig.keys, generatorConfigDefaultJson.keys); + }); + for (final entry in _invalidConfig.entries) { + test(entry.key, () { + final config = Map.from(generatorConfigDefaultJson); + config[entry.key] = entry.value; + + final lastLine = entry.key == 'field_rename' + ? '`42` is not one of the supported values: none, kebab, snake, ' + 'pascal' + : "type 'int' is not a subtype of type 'bool' in type cast"; + + final matcher = isA().having( + (v) => v.message, + 'message', + ''' +Could not parse the options provided for `json_serializable`. +There is a problem with "${entry.key}". +$lastLine''', + ); + expect( + () => jsonSerializable(BuilderOptions(config)), throwsA(matcher)); + }); + } + }); +} + +const _invalidConfig = { + 'any_map': 42, + 'checked': 42, + 'create_factory': 42, + 'create_to_json': 42, + 'disallow_unrecognized_keys': 42, + 'explicit_to_json': 42, + 'field_rename': 42, + 'generic_argument_factories': 42, + 'ignore_unannotated': 42, + 'include_if_null': 42, + 'nullable': 42, +}; diff --git a/json_serializable-3.5.2/test/custom_configuration_test.dart b/json_serializable-3.5.2/test/custom_configuration_test.dart new file mode 100644 index 000000000..87857934b --- /dev/null +++ b/json_serializable-3.5.2/test/custom_configuration_test.dart @@ -0,0 +1,222 @@ +// Copyright (c) 2015, 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. + +@TestOn('vm') +import 'dart:async'; + +import 'package:analyzer/dart/element/type.dart'; +import 'package:json_annotation/json_annotation.dart'; +import 'package:json_serializable/json_serializable.dart'; +import 'package:json_serializable/src/constants.dart'; +import 'package:json_serializable/src/type_helper.dart'; +import 'package:path/path.dart' as p; +import 'package:source_gen/source_gen.dart'; +import 'package:source_gen_test/source_gen_test.dart'; +import 'package:test/test.dart'; + +import 'shared_config.dart'; + +LibraryReader _libraryReader; + +Future main() async { + initializeBuildLogTracking(); + _libraryReader = await initializeLibraryReaderForDirectory( + p.join('test', 'test_sources'), + 'test_sources.dart', + ); + + group('without wrappers', () { + _registerTests(JsonSerializable.defaults); + }); + + group('configuration', () { + Future runWithConfigAndLogger( + JsonSerializable config, String className) async { + await generateForElement( + JsonSerializableGenerator( + config: config, typeHelpers: const [_ConfigLogger()]), + _libraryReader, + className); + } + + setUp(_ConfigLogger.configurations.clear); + + group('defaults', () { + for (var className in [ + 'ConfigurationImplicitDefaults', + 'ConfigurationExplicitDefaults', + ]) { + for (var nullConfig in [true, false]) { + final testDescription = + '$className with ${nullConfig ? 'null' : 'default'} config'; + + test(testDescription, () async { + await runWithConfigAndLogger( + nullConfig ? null : const JsonSerializable(), className); + + expect(_ConfigLogger.configurations, hasLength(2)); + expect(_ConfigLogger.configurations.first, + same(_ConfigLogger.configurations.last)); + expect(_ConfigLogger.configurations.first.toJson(), + generatorConfigDefaultJson); + }); + } + } + }); + + test( + 'values in config override unconfigured (default) values in annotation', + () async { + await runWithConfigAndLogger( + JsonSerializable.fromJson(generatorConfigNonDefaultJson), + 'ConfigurationImplicitDefaults'); + + expect(_ConfigLogger.configurations, isEmpty, + reason: 'all generation is disabled'); + + // Create a configuration with just `create_to_json` set to true so we + // can validate the configuration that is run with + final configMap = + Map.from(generatorConfigNonDefaultJson); + configMap['create_to_json'] = true; + + await runWithConfigAndLogger(JsonSerializable.fromJson(configMap), + 'ConfigurationImplicitDefaults'); + }); + + test( + 'explicit values in annotation override corresponding settings in config', + () async { + await runWithConfigAndLogger( + JsonSerializable.fromJson(generatorConfigNonDefaultJson), + 'ConfigurationExplicitDefaults'); + + expect(_ConfigLogger.configurations, hasLength(2)); + expect(_ConfigLogger.configurations.first, + same(_ConfigLogger.configurations.last)); + + // The effective configuration should be non-Default configuration, but + // with all fields set from JsonSerializable as the defaults + + final expected = + Map.from(generatorConfigNonDefaultJson); + for (var jsonSerialKey in jsonSerializableFields) { + expected[jsonSerialKey] = generatorConfigDefaultJson[jsonSerialKey]; + } + + expect(_ConfigLogger.configurations.first.toJson(), expected); + }, + ); + }); +} + +Future _runForElementNamed(JsonSerializable config, String name) async { + final generator = JsonSerializableGenerator(config: config); + return generateForElement(generator, _libraryReader, name); +} + +void _registerTests(JsonSerializable generator) { + Future runForElementNamed(String name) => + _runForElementNamed(generator, name); + + group('explicit toJson', () { + test('nullable', () async { + final output = await _runForElementNamed( + const JsonSerializable(), 'TrivialNestedNullable'); + + const expected = r''' +Map _$TrivialNestedNullableToJson( + TrivialNestedNullable instance) => + { + 'child': instance.child?.toJson(), + 'otherField': instance.otherField, + }; +'''; + + expect(output, expected); + }); + test('non-nullable', () async { + final output = await _runForElementNamed( + const JsonSerializable(), 'TrivialNestedNonNullable'); + + const expected = r''' +Map _$TrivialNestedNonNullableToJson( + TrivialNestedNonNullable instance) => + { + 'child': instance.child.toJson(), + 'otherField': instance.otherField, + }; +'''; + + expect(output, expected); + }); + }); + + group('valid inputs', () { + test('class with fromJson() constructor with optional parameters', + () async { + final output = await runForElementNamed('FromJsonOptionalParameters'); + + expect(output, contains('ChildWithFromJson.fromJson')); + }); + + test('class with child json-able object', () async { + final output = await runForElementNamed('ParentObject'); + + expect( + output, + contains("ChildObject.fromJson(json['child'] " + 'as Map)')); + }); + + test('class with child json-able object - anyMap', () async { + final output = await _runForElementNamed( + const JsonSerializable(anyMap: true), 'ParentObject'); + + expect(output, contains("ChildObject.fromJson(json['child'] as Map)")); + }); + + test('class with child list of json-able objects', () async { + final output = await runForElementNamed('ParentObjectWithChildren'); + + expect(output, contains('.toList()')); + expect(output, contains('ChildObject.fromJson')); + }); + + test('class with child list of dynamic objects is left alone', () async { + final output = + await runForElementNamed('ParentObjectWithDynamicChildren'); + + expect(output, contains('children = json[\'children\'] as List;')); + }); + }); + + group('includeIfNull', () { + test('some', () async { + final output = await runForElementNamed('IncludeIfNullAll'); + expect(output, isNot(contains(generatedLocalVarName))); + expect(output, isNot(contains(toJsonMapHelperName))); + }); + }); +} + +class _ConfigLogger implements TypeHelper { + static final configurations = []; + + const _ConfigLogger(); + + @override + Object deserialize(DartType targetType, String expression, + TypeHelperContextWithConfig context) { + configurations.add(context.config); + return null; + } + + @override + Object serialize(DartType targetType, String expression, + TypeHelperContextWithConfig context) { + configurations.add(context.config); + return null; + } +} diff --git a/json_serializable-3.5.2/test/default_value/default_value.dart b/json_serializable-3.5.2/test/default_value/default_value.dart new file mode 100644 index 000000000..083c60d05 --- /dev/null +++ b/json_serializable-3.5.2/test/default_value/default_value.dart @@ -0,0 +1,65 @@ +// 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. + +// ignore_for_file: annotate_overrides + +import 'package:json_annotation/json_annotation.dart'; + +import 'default_value_interface.dart' as dvi hide Greek; +import 'default_value_interface.dart' show Greek; + +part 'default_value.g.dart'; + +const _intValue = 42; + +dvi.DefaultValue fromJson(Map json) => + _$DefaultValueFromJson(json); + +@JsonSerializable() +class DefaultValue implements dvi.DefaultValue { + @JsonKey(defaultValue: true) + bool fieldBool; + + @JsonKey(defaultValue: 'string', includeIfNull: false) + String fieldString; + + @JsonKey(defaultValue: _intValue) + int fieldInt; + + @JsonKey(defaultValue: 3.14) + double fieldDouble; + + @JsonKey(defaultValue: []) + List fieldListEmpty; + + @JsonKey(defaultValue: {}) + Set fieldSetEmpty; + + @JsonKey(defaultValue: {}) + Map fieldMapEmpty; + + @JsonKey(defaultValue: [1, 2, 3]) + List fieldListSimple; + + @JsonKey(defaultValue: {'entry1', 'entry2'}) + Set fieldSetSimple; + + @JsonKey(defaultValue: {'answer': 42}) + Map fieldMapSimple; + + @JsonKey(defaultValue: { + 'root': ['child'] + }) + Map> fieldMapListString; + + @JsonKey(defaultValue: Greek.beta) + Greek fieldEnum; + + DefaultValue(); + + factory DefaultValue.fromJson(Map json) => + _$DefaultValueFromJson(json); + + Map toJson() => _$DefaultValueToJson(this); +} diff --git a/json_serializable-3.5.2/test/default_value/default_value.g.dart b/json_serializable-3.5.2/test/default_value/default_value.g.dart new file mode 100644 index 000000000..95bcdd973 --- /dev/null +++ b/json_serializable-3.5.2/test/default_value/default_value.g.dart @@ -0,0 +1,102 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'default_value.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +DefaultValue _$DefaultValueFromJson(Map json) { + return DefaultValue() + ..fieldBool = json['fieldBool'] as bool ?? true + ..fieldString = json['fieldString'] as String ?? 'string' + ..fieldInt = json['fieldInt'] as int ?? 42 + ..fieldDouble = (json['fieldDouble'] as num)?.toDouble() ?? 3.14 + ..fieldListEmpty = json['fieldListEmpty'] as List ?? [] + ..fieldSetEmpty = (json['fieldSetEmpty'] as List)?.toSet() ?? {} + ..fieldMapEmpty = json['fieldMapEmpty'] as Map ?? {} + ..fieldListSimple = + (json['fieldListSimple'] as List)?.map((e) => e as int)?.toList() ?? + [1, 2, 3] + ..fieldSetSimple = + (json['fieldSetSimple'] as List)?.map((e) => e as String)?.toSet() ?? + {'entry1', 'entry2'} + ..fieldMapSimple = (json['fieldMapSimple'] as Map)?.map( + (k, e) => MapEntry(k, e as int), + ) ?? + {'answer': 42} + ..fieldMapListString = + (json['fieldMapListString'] as Map)?.map( + (k, e) => + MapEntry(k, (e as List)?.map((e) => e as String)?.toList()), + ) ?? + { + 'root': ['child'] + } + ..fieldEnum = + _$enumDecodeNullable(_$GreekEnumMap, json['fieldEnum']) ?? Greek.beta; +} + +Map _$DefaultValueToJson(DefaultValue instance) { + final val = { + 'fieldBool': instance.fieldBool, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('fieldString', instance.fieldString); + val['fieldInt'] = instance.fieldInt; + val['fieldDouble'] = instance.fieldDouble; + val['fieldListEmpty'] = instance.fieldListEmpty; + val['fieldSetEmpty'] = instance.fieldSetEmpty?.toList(); + val['fieldMapEmpty'] = instance.fieldMapEmpty; + val['fieldListSimple'] = instance.fieldListSimple; + val['fieldSetSimple'] = instance.fieldSetSimple?.toList(); + val['fieldMapSimple'] = instance.fieldMapSimple; + val['fieldMapListString'] = instance.fieldMapListString; + val['fieldEnum'] = _$GreekEnumMap[instance.fieldEnum]; + return val; +} + +T _$enumDecode( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} + +T _$enumDecodeNullable( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode(enumValues, source, unknownValue: unknownValue); +} + +const _$GreekEnumMap = { + Greek.alpha: 'alpha', + Greek.beta: 'beta', + Greek.gamma: 'gamma', + Greek.delta: 'delta', +}; diff --git a/json_serializable-3.5.2/test/default_value/default_value.g_any_map__checked.dart b/json_serializable-3.5.2/test/default_value/default_value.g_any_map__checked.dart new file mode 100644 index 000000000..d0b3ffae5 --- /dev/null +++ b/json_serializable-3.5.2/test/default_value/default_value.g_any_map__checked.dart @@ -0,0 +1,68 @@ +// 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. + +// ignore_for_file: annotate_overrides + +import 'package:json_annotation/json_annotation.dart'; + +import 'default_value_interface.dart' as dvi hide Greek; +import 'default_value_interface.dart' show Greek; + +part 'default_value.g_any_map__checked.g.dart'; + +const _intValue = 42; + +dvi.DefaultValue fromJson(Map json) => + _$DefaultValueFromJson(json); + +@JsonSerializable( + checked: true, + anyMap: true, +) +class DefaultValue implements dvi.DefaultValue { + @JsonKey(defaultValue: true) + bool fieldBool; + + @JsonKey(defaultValue: 'string', includeIfNull: false) + String fieldString; + + @JsonKey(defaultValue: _intValue) + int fieldInt; + + @JsonKey(defaultValue: 3.14) + double fieldDouble; + + @JsonKey(defaultValue: []) + List fieldListEmpty; + + @JsonKey(defaultValue: {}) + Set fieldSetEmpty; + + @JsonKey(defaultValue: {}) + Map fieldMapEmpty; + + @JsonKey(defaultValue: [1, 2, 3]) + List fieldListSimple; + + @JsonKey(defaultValue: {'entry1', 'entry2'}) + Set fieldSetSimple; + + @JsonKey(defaultValue: {'answer': 42}) + Map fieldMapSimple; + + @JsonKey(defaultValue: { + 'root': ['child'] + }) + Map> fieldMapListString; + + @JsonKey(defaultValue: Greek.beta) + Greek fieldEnum; + + DefaultValue(); + + factory DefaultValue.fromJson(Map json) => + _$DefaultValueFromJson(json); + + Map toJson() => _$DefaultValueToJson(this); +} diff --git a/json_serializable-3.5.2/test/default_value/default_value.g_any_map__checked.g.dart b/json_serializable-3.5.2/test/default_value/default_value.g_any_map__checked.g.dart new file mode 100644 index 000000000..528e085e1 --- /dev/null +++ b/json_serializable-3.5.2/test/default_value/default_value.g_any_map__checked.g.dart @@ -0,0 +1,124 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'default_value.g_any_map__checked.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +DefaultValue _$DefaultValueFromJson(Map json) { + return $checkedNew('DefaultValue', json, () { + final val = DefaultValue(); + $checkedConvert( + json, 'fieldBool', (v) => val.fieldBool = v as bool ?? true); + $checkedConvert( + json, 'fieldString', (v) => val.fieldString = v as String ?? 'string'); + $checkedConvert(json, 'fieldInt', (v) => val.fieldInt = v as int ?? 42); + $checkedConvert(json, 'fieldDouble', + (v) => val.fieldDouble = (v as num)?.toDouble() ?? 3.14); + $checkedConvert( + json, 'fieldListEmpty', (v) => val.fieldListEmpty = v as List ?? []); + $checkedConvert(json, 'fieldSetEmpty', + (v) => val.fieldSetEmpty = (v as List)?.toSet() ?? {}); + $checkedConvert( + json, 'fieldMapEmpty', (v) => val.fieldMapEmpty = v as Map ?? {}); + $checkedConvert( + json, + 'fieldListSimple', + (v) => val.fieldListSimple = + (v as List)?.map((e) => e as int)?.toList() ?? [1, 2, 3]); + $checkedConvert( + json, + 'fieldSetSimple', + (v) => val.fieldSetSimple = + (v as List)?.map((e) => e as String)?.toSet() ?? + {'entry1', 'entry2'}); + $checkedConvert( + json, + 'fieldMapSimple', + (v) => val.fieldMapSimple = (v as Map)?.map( + (k, e) => MapEntry(k as String, e as int), + ) ?? + {'answer': 42}); + $checkedConvert( + json, + 'fieldMapListString', + (v) => val.fieldMapListString = (v as Map)?.map( + (k, e) => MapEntry( + k as String, (e as List)?.map((e) => e as String)?.toList()), + ) ?? + { + 'root': ['child'] + }); + $checkedConvert( + json, + 'fieldEnum', + (v) => val.fieldEnum = + _$enumDecodeNullable(_$GreekEnumMap, v) ?? Greek.beta); + return val; + }); +} + +Map _$DefaultValueToJson(DefaultValue instance) { + final val = { + 'fieldBool': instance.fieldBool, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('fieldString', instance.fieldString); + val['fieldInt'] = instance.fieldInt; + val['fieldDouble'] = instance.fieldDouble; + val['fieldListEmpty'] = instance.fieldListEmpty; + val['fieldSetEmpty'] = instance.fieldSetEmpty?.toList(); + val['fieldMapEmpty'] = instance.fieldMapEmpty; + val['fieldListSimple'] = instance.fieldListSimple; + val['fieldSetSimple'] = instance.fieldSetSimple?.toList(); + val['fieldMapSimple'] = instance.fieldMapSimple; + val['fieldMapListString'] = instance.fieldMapListString; + val['fieldEnum'] = _$GreekEnumMap[instance.fieldEnum]; + return val; +} + +T _$enumDecode( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} + +T _$enumDecodeNullable( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode(enumValues, source, unknownValue: unknownValue); +} + +const _$GreekEnumMap = { + Greek.alpha: 'alpha', + Greek.beta: 'beta', + Greek.gamma: 'gamma', + Greek.delta: 'delta', +}; diff --git a/json_serializable-3.5.2/test/default_value/default_value_interface.dart b/json_serializable-3.5.2/test/default_value/default_value_interface.dart new file mode 100644 index 000000000..957889694 --- /dev/null +++ b/json_serializable-3.5.2/test/default_value/default_value_interface.dart @@ -0,0 +1,24 @@ +// 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. + +// 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. + +abstract class DefaultValue { + bool fieldBool; + String fieldString; + int fieldInt; + double fieldDouble; + List fieldListEmpty; + Map fieldMapEmpty; + Set fieldSetEmpty; + List fieldListSimple; + Set fieldSetSimple; + Map fieldMapSimple; + Map> fieldMapListString; + Greek fieldEnum; +} + +enum Greek { alpha, beta, gamma, delta } diff --git a/json_serializable-3.5.2/test/default_value/default_value_test.dart b/json_serializable-3.5.2/test/default_value/default_value_test.dart new file mode 100644 index 000000000..00ef236ad --- /dev/null +++ b/json_serializable-3.5.2/test/default_value/default_value_test.dart @@ -0,0 +1,64 @@ +// 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. + +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'default_value.dart' as normal; +import 'default_value.g_any_map__checked.dart' as checked; +import 'default_value_interface.dart'; + +const _defaultInstance = { + 'fieldBool': true, + 'fieldString': 'string', + 'fieldInt': 42, + 'fieldDouble': 3.14, + 'fieldListEmpty': [], + 'fieldSetEmpty': [], + 'fieldMapEmpty': {}, + 'fieldListSimple': [1, 2, 3], + 'fieldSetSimple': ['entry1', 'entry2'], + 'fieldMapSimple': {'answer': 42}, + 'fieldMapListString': { + 'root': ['child'] + }, + 'fieldEnum': 'beta' +}; + +const _otherValues = { + 'fieldBool': false, + 'fieldString': 'other string', + 'fieldInt': 43, + 'fieldDouble': 2.718, + 'fieldListEmpty': [42], + 'fieldSetEmpty': [42], + 'fieldMapEmpty': {'question': false}, + 'fieldListSimple': [4, 5, 6], + 'fieldSetSimple': ['entry3'], + 'fieldMapSimple': {}, + 'fieldMapListString': { + 'root2': ['alpha'] + }, + 'fieldEnum': 'delta' +}; + +void main() { + group('nullable', () => _test(normal.fromJson)); + group('non-nullable', () => _test(checked.fromJson)); +} + +void _test(DefaultValue Function(Map json) fromJson) { + test('empty map yields all default values', () { + final object = fromJson({}); + expect(loudEncode(object), loudEncode(_defaultInstance)); + }); + test('default value input round-trips', () { + final object = fromJson(_defaultInstance); + expect(loudEncode(object), loudEncode(_defaultInstance)); + }); + test('non-default values round-trip', () { + final object = fromJson(_otherValues); + expect(loudEncode(object), loudEncode(_otherValues)); + }); +} diff --git a/json_serializable-3.5.2/test/ensure_build_test.dart b/json_serializable-3.5.2/test/ensure_build_test.dart new file mode 100644 index 000000000..487646cb3 --- /dev/null +++ b/json_serializable-3.5.2/test/ensure_build_test.dart @@ -0,0 +1,13 @@ +// Copyright (c) 2017, 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. + +@TestOn('vm') +@Tags(['presubmit-only']) +import 'package:build_verify/build_verify.dart'; +import 'package:test/test.dart'; + +void main() { + test('ensure_build', + () => expectBuildClean(packageRelativeDirectory: 'json_serializable')); +} diff --git a/json_serializable-3.5.2/test/enum_helper_test.dart b/json_serializable-3.5.2/test/enum_helper_test.dart new file mode 100644 index 000000000..8043543b7 --- /dev/null +++ b/json_serializable-3.5.2/test/enum_helper_test.dart @@ -0,0 +1,34 @@ +// Copyright (c) 2017, 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. + +@TestOn('vm') + +import 'package:test/test.dart'; +import 'package:json_serializable/src/type_helpers/enum_helper.dart'; + +void main() { + group('expression test', () { + group('simple', () { + for (final expression in [ + 'hello', + 'HELLO', + 'hi_to', + '_private', + 'weird_' + ]) { + test(expression, () { + expect(simpleExpression.hasMatch(expression), isTrue); + }); + } + }); + + group('not simple', () { + for (final expression in ['nice[thing]', 'a.b']) { + test(expression, () { + expect(simpleExpression.hasMatch(expression), isFalse); + }); + } + }); + }); +} diff --git a/json_serializable-3.5.2/test/generic_files/generic_argument_factories.dart b/json_serializable-3.5.2/test/generic_files/generic_argument_factories.dart new file mode 100644 index 000000000..47d9987cf --- /dev/null +++ b/json_serializable-3.5.2/test/generic_files/generic_argument_factories.dart @@ -0,0 +1,49 @@ +// 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'generic_argument_factories.g.dart'; + +@JsonSerializable(genericArgumentFactories: true) +class GenericClassWithHelpers { + final T value; + + final List list; + + final Set someSet; + + GenericClassWithHelpers( + this.value, + this.list, + this.someSet, + ); + + factory GenericClassWithHelpers.fromJson( + Map json, + T Function(Object json) fromJsonT, + S Function(Object json) fromJsonS, + ) => + _$GenericClassWithHelpersFromJson(json, fromJsonT, fromJsonS); + + Map toJson( + Object Function(T value) toJsonT, + Object Function(S value) toJsonS, + ) => + _$GenericClassWithHelpersToJson(this, toJsonT, toJsonS); +} + +@JsonSerializable() +class ConcreteClass { + final GenericClassWithHelpers value; + + final GenericClassWithHelpers value2; + + ConcreteClass(this.value, this.value2); + + factory ConcreteClass.fromJson(Map json) => + _$ConcreteClassFromJson(json); + + Map toJson() => _$ConcreteClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/generic_files/generic_argument_factories.g.dart b/json_serializable-3.5.2/test/generic_files/generic_argument_factories.g.dart new file mode 100644 index 000000000..b88167ada --- /dev/null +++ b/json_serializable-3.5.2/test/generic_files/generic_argument_factories.g.dart @@ -0,0 +1,59 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'generic_argument_factories.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +GenericClassWithHelpers _$GenericClassWithHelpersFromJson( + Map json, + T Function(Object json) fromJsonT, + S Function(Object json) fromJsonS, +) { + return GenericClassWithHelpers( + fromJsonT(json['value']), + (json['list'] as List)?.map(fromJsonT)?.toList(), + (json['someSet'] as List)?.map(fromJsonS)?.toSet(), + ); +} + +Map _$GenericClassWithHelpersToJson( + GenericClassWithHelpers instance, + Object Function(T value) toJsonT, + Object Function(S value) toJsonS, +) => + { + 'value': toJsonT(instance.value), + 'list': instance.list?.map(toJsonT)?.toList(), + 'someSet': instance.someSet?.map(toJsonS)?.toList(), + }; + +ConcreteClass _$ConcreteClassFromJson(Map json) { + return ConcreteClass( + json['value'] == null + ? null + : GenericClassWithHelpers.fromJson( + json['value'] as Map, + (value) => value as int, + (value) => value as String), + json['value2'] == null + ? null + : GenericClassWithHelpers.fromJson( + json['value2'] as Map, + (value) => (value as num)?.toDouble(), + (value) => value == null ? null : BigInt.parse(value as String)), + ); +} + +Map _$ConcreteClassToJson(ConcreteClass instance) => + { + 'value': instance.value?.toJson( + (value) => value, + (value) => value, + ), + 'value2': instance.value2?.toJson( + (value) => value, + (value) => value?.toString(), + ), + }; diff --git a/json_serializable-3.5.2/test/generic_files/generic_class.dart b/json_serializable-3.5.2/test/generic_files/generic_class.dart new file mode 100644 index 000000000..b7cdf649c --- /dev/null +++ b/json_serializable-3.5.2/test/generic_files/generic_class.dart @@ -0,0 +1,104 @@ +// 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'generic_class.g.dart'; + +@JsonSerializable() +class GenericClass { + @JsonKey(fromJson: _dataFromJson, toJson: _dataToJson) + Object fieldObject; + + @JsonKey(fromJson: _dataFromJson, toJson: _dataToJson) + dynamic fieldDynamic; + + @JsonKey(fromJson: _dataFromJson, toJson: _dataToJson) + int fieldInt; + + @JsonKey(fromJson: _dataFromJson, toJson: _dataToJson) + T fieldT; + + @JsonKey(fromJson: _dataFromJson, toJson: _dataToJson) + S fieldS; + + GenericClass(); + + factory GenericClass.fromJson(Map json) => + _$GenericClassFromJson(json); + + Map toJson() => _$GenericClassToJson(this); + + static T _dataFromJson(Map input, + [S other1, U other2]) => + input['value'] as T; + + static Map _dataToJson(T input, + [S other1, U other2]) => + {'value': input}; +} + +@JsonSerializable() +@_DurationMillisecondConverter.named() +@_DurationListMillisecondConverter() +class GenericClassWithConverter { + @_SimpleConverter() + Object fieldObject; + + @_SimpleConverter() + dynamic fieldDynamic; + + @_SimpleConverter() + int fieldInt; + + @_SimpleConverter() + T fieldT; + + @_SimpleConverter() + S fieldS; + + Duration duration; + + List listDuration; + + GenericClassWithConverter(); + + factory GenericClassWithConverter.fromJson(Map json) => + _$GenericClassWithConverterFromJson(json); + + Map toJson() => _$GenericClassWithConverterToJson(this); +} + +class _SimpleConverter implements JsonConverter> { + const _SimpleConverter(); + + @override + T fromJson(Map json) => json['value'] as T; + + @override + Map toJson(T object) => {'value': object}; +} + +class _DurationMillisecondConverter implements JsonConverter { + const _DurationMillisecondConverter.named(); + + @override + Duration fromJson(int json) => + json == null ? null : Duration(milliseconds: json); + + @override + int toJson(Duration object) => object?.inMilliseconds; +} + +class _DurationListMillisecondConverter + implements JsonConverter, int> { + const _DurationListMillisecondConverter(); + + @override + List fromJson(int json) => [Duration(milliseconds: json)]; + + @override + int toJson(List object) => + object?.fold(0, (sum, obj) => sum + obj.inMilliseconds); +} diff --git a/json_serializable-3.5.2/test/generic_files/generic_class.g.dart b/json_serializable-3.5.2/test/generic_files/generic_class.g.dart new file mode 100644 index 000000000..ae3c03aad --- /dev/null +++ b/json_serializable-3.5.2/test/generic_files/generic_class.g.dart @@ -0,0 +1,63 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'generic_class.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +GenericClass _$GenericClassFromJson( + Map json) { + return GenericClass() + ..fieldObject = + GenericClass._dataFromJson(json['fieldObject'] as Map) + ..fieldDynamic = + GenericClass._dataFromJson(json['fieldDynamic'] as Map) + ..fieldInt = + GenericClass._dataFromJson(json['fieldInt'] as Map) + ..fieldT = + GenericClass._dataFromJson(json['fieldT'] as Map) + ..fieldS = + GenericClass._dataFromJson(json['fieldS'] as Map); +} + +Map _$GenericClassToJson( + GenericClass instance) => + { + 'fieldObject': GenericClass._dataToJson(instance.fieldObject), + 'fieldDynamic': GenericClass._dataToJson(instance.fieldDynamic), + 'fieldInt': GenericClass._dataToJson(instance.fieldInt), + 'fieldT': GenericClass._dataToJson(instance.fieldT), + 'fieldS': GenericClass._dataToJson(instance.fieldS), + }; + +GenericClassWithConverter + _$GenericClassWithConverterFromJson( + Map json) { + return GenericClassWithConverter() + ..fieldObject = json['fieldObject'] + ..fieldDynamic = json['fieldDynamic'] + ..fieldInt = json['fieldInt'] as int + ..fieldT = + _SimpleConverter().fromJson(json['fieldT'] as Map) + ..fieldS = + _SimpleConverter().fromJson(json['fieldS'] as Map) + ..duration = const _DurationMillisecondConverter.named() + .fromJson(json['duration'] as int) + ..listDuration = const _DurationListMillisecondConverter() + .fromJson(json['listDuration'] as int); +} + +Map _$GenericClassWithConverterToJson( + GenericClassWithConverter instance) => + { + 'fieldObject': instance.fieldObject, + 'fieldDynamic': instance.fieldDynamic, + 'fieldInt': instance.fieldInt, + 'fieldT': _SimpleConverter().toJson(instance.fieldT), + 'fieldS': _SimpleConverter().toJson(instance.fieldS), + 'duration': + const _DurationMillisecondConverter.named().toJson(instance.duration), + 'listDuration': const _DurationListMillisecondConverter() + .toJson(instance.listDuration), + }; diff --git a/json_serializable-3.5.2/test/generic_files/generic_test.dart b/json_serializable-3.5.2/test/generic_files/generic_test.dart new file mode 100644 index 000000000..19c43758a --- /dev/null +++ b/json_serializable-3.5.2/test/generic_files/generic_test.dart @@ -0,0 +1,118 @@ +// 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. + +import 'dart:convert'; + +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'generic_argument_factories.dart'; +import 'generic_class.dart'; + +void main() { + group('generic', () { + GenericClass roundTripGenericClass( + GenericClass p) { + final outputJson = loudEncode(p); + final p2 = GenericClass.fromJson( + jsonDecode(outputJson) as Map); + final outputJson2 = loudEncode(p2); + expect(outputJson2, outputJson); + return p2; + } + + test('no type args', () { + roundTripGenericClass(GenericClass() + ..fieldDynamic = 1 + ..fieldInt = 2 + ..fieldObject = 3 + ..fieldT = 5 + ..fieldS = 'six'); + }); + test('with type arguments', () { + roundTripGenericClass(GenericClass() + ..fieldDynamic = 1 + ..fieldInt = 2 + ..fieldObject = 3 + ..fieldT = 5.0 + ..fieldS = 'six'); + }); + test('with bad arguments', () { + expect( + () => GenericClass() + ..fieldT = (true as dynamic) as double, + throwsCastError); + }); + test('with bad arguments', () { + expect( + () => + GenericClass()..fieldS = (5 as dynamic) as String, + throwsCastError); + }); + }); + + group('genericArgumentFactories', () { + test('basic round-trip', () { + final instance = GenericClassWithHelpers( + DateTime.fromMillisecondsSinceEpoch(0).toUtc(), + [ + DateTime.fromMillisecondsSinceEpoch(1).toUtc(), + DateTime.fromMillisecondsSinceEpoch(2).toUtc(), + ], + {const Duration(milliseconds: 3), const Duration(milliseconds: 4)}, + ); + + String encodeDateTime(DateTime value) => value?.toIso8601String(); + int encodeDuration(Duration value) => value.inMilliseconds; + + final encodedJson = loudEncode( + instance.toJson(encodeDateTime, encodeDuration), + ); + + final decoded = GenericClassWithHelpers.fromJson( + jsonDecode(encodedJson) as Map, + (value) => DateTime.parse(value as String), + (value) => Duration(milliseconds: value as int), + ); + + final encodedJson2 = loudEncode( + decoded.toJson(encodeDateTime, encodeDuration), + ); + + expect(encodedJson2, encodedJson); + }); + }); + + group('argument factories', () { + test('round trip decode/decode', () { + const inputJson = r''' +{ + "value": { + "value": 5, + "list": [ + 5 + ], + "someSet": [ + "string" + ] + }, + "value2": { + "value": 3.14, + "list": [ + 3.14 + ], + "someSet": [ + "2" + ] + } +}'''; + + final instance = ConcreteClass.fromJson( + jsonDecode(inputJson) as Map, + ); + + expect(loudEncode(instance), inputJson); + }); + }); +} diff --git a/json_serializable-3.5.2/test/integration/integration_test.dart b/json_serializable-3.5.2/test/integration/integration_test.dart new file mode 100644 index 000000000..fa51cfbe2 --- /dev/null +++ b/json_serializable-3.5.2/test/integration/integration_test.dart @@ -0,0 +1,283 @@ +// Copyright (c) 2015, 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. + +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'json_test_common.dart' show Category, Platform, StatusCode; +import 'json_test_example.dart'; + +Matcher _throwsArgumentError(matcher) => + throwsA(isArgumentError.having((e) => e.message, 'message', matcher)); + +void main() { + group('Person', () { + void roundTripPerson(Person p) { + roundTripObject(p, (json) => Person.fromJson(json)); + } + + test('null', () { + roundTripPerson(Person(null, null, null)); + }); + + test('empty', () { + roundTripPerson(Person('', '', null, + middleName: '', dateOfBirth: DateTime.fromMillisecondsSinceEpoch(0))); + }); + + test('now', () { + roundTripPerson(Person('a', 'b', Category.charmed, + middleName: 'c', dateOfBirth: DateTime.now())); + }); + + test('now toUtc', () { + roundTripPerson(Person('a', 'b', Category.bottom, + middleName: 'c', dateOfBirth: DateTime.now().toUtc())); + }); + + test('empty json', () { + final person = Person.fromJson({}); + expect(person.dateOfBirth, isNull); + roundTripPerson(person); + }); + + test('enum map', () { + final person = Person(null, null, null) + ..houseMap = {'bob': Category.strange} + ..categoryCounts = {Category.strange: 1}; + expect(person.dateOfBirth, isNull); + roundTripPerson(person); + }); + }); + + group('Order', () { + void roundTripOrder(Order p) { + roundTripObject(p, (json) => Order.fromJson(json)); + } + + test('null', () { + roundTripOrder(Order(Category.charmed)..statusCode = StatusCode.success); + }); + + test('empty', () { + roundTripOrder(Order(Category.strange, const []) + ..statusCode = StatusCode.success + ..count = 0 + ..isRushed = false); + }); + + test('simple', () { + roundTripOrder(Order(Category.top, [ + Item(24) + ..itemNumber = 42 + ..saleDates = [DateTime.now()] + ]) + ..statusCode = StatusCode.success + ..count = 42 + ..isRushed = true); + }); + + test('almost empty json', () { + final order = Order.fromJson({'category': 'not_discovered_yet'}); + expect(order.items, isEmpty); + expect(order.category, Category.notDiscoveredYet); + expect( + order.statusCode, + StatusCode.success, + reason: 'success is the default on an unset value', + ); + roundTripOrder(order); + }); + + test('required, but missing enum value fails', () { + expect( + () => Order.fromJson({}), + _throwsArgumentError('A value must be provided. Supported values: ' + 'top, bottom, strange, charmed, up, down, not_discovered_yet')); + }); + + test('mismatched enum value fails', () { + expect( + () => Order.fromJson({'category': 'weird'}), + _throwsArgumentError('`weird` is not one of the supported values: ' + 'top, bottom, strange, charmed, up, down, not_discovered_yet')); + }); + + test('platform', () { + final order = Order(Category.charmed) + ..statusCode = StatusCode.success + ..platform = Platform.undefined + ..altPlatforms = { + 'u': Platform.undefined, + 'f': Platform.foo, + 'null': null + }; + + roundTripOrder(order); + }); + + test('homepage', () { + final order = Order(Category.charmed) + ..platform = Platform.undefined + ..statusCode = StatusCode.success + ..altPlatforms = { + 'u': Platform.undefined, + 'f': Platform.foo, + 'null': null + } + ..homepage = Uri.parse('https://dart.dev'); + + roundTripOrder(order); + }); + + test('statusCode', () { + final order = Order.fromJson( + {'category': 'not_discovered_yet', 'status_code': 404}, + ); + expect(order.statusCode, StatusCode.notFound); + roundTripOrder(order); + }); + + test('statusCode "500" - weird', () { + final order = Order.fromJson( + {'category': 'not_discovered_yet', 'status_code': '500'}, + ); + expect(order.statusCode, StatusCode.weird); + roundTripOrder(order); + }); + + test('statusCode `500` - unknown', () { + final order = Order.fromJson( + {'category': 'not_discovered_yet', 'status_code': 500}, + ); + expect(order.statusCode, StatusCode.unknown); + roundTripOrder(order); + }); + + test('duration toJson', () { + final order = Order(Category.notDiscoveredYet) + ..statusCode = StatusCode.success + ..duration = const Duration( + days: 2, + hours: 4, + minutes: 54, + seconds: 33, + milliseconds: 23, + microseconds: 12, + ); + expect(order.toJson()['duration'], equals(190473023012)); + roundTripOrder(order); + }); + + test('duration fromJson', () { + final order = Order.fromJson({ + 'category': 'not_discovered_yet', + 'duration': 190473023012, + }); + expect( + order.duration, + equals(const Duration( + days: 2, + hours: 4, + minutes: 54, + seconds: 33, + milliseconds: 23, + microseconds: 12, + ))); + roundTripOrder(order); + }); + }); + + group('Item', () { + void roundTripItem(Item p) { + roundTripObject(p, (json) => Item.fromJson(json)); + } + + test('empty json', () { + final item = Item.fromJson({}); + expect(item.saleDates, isNull); + roundTripItem(item); + + expect(item.toJson().keys, orderedEquals(['price', 'saleDates', 'rates']), + reason: 'Omits null `itemNumber`'); + }); + + test('set itemNumber - with custom JSON key', () { + final item = Item.fromJson({'item-number': 42}); + expect(item.itemNumber, 42); + roundTripItem(item); + + expect(item.toJson().keys, + orderedEquals(['price', 'item-number', 'saleDates', 'rates']), + reason: 'Includes non-null `itemNumber` - with custom key'); + }); + }); + + group('Numbers', () { + void roundTripNumber(Numbers p) { + roundTripObject(p, (json) => Numbers.fromJson(json)); + } + + test('simple', () { + roundTripNumber(Numbers() + ..nums = [0, 0.0] + ..doubles = [0.0] + ..nnDoubles = [0.0] + ..ints = [0] + ..duration = const Duration(seconds: 1) + ..date = DateTime.now()); + }); + + test('custom DateTime', () { + final instance = Numbers() + ..date = DateTime.fromMillisecondsSinceEpoch(42); + final json = instance.toJson(); + expect(json, containsPair('date', 42000)); + }); + + test('support ints as doubles', () { + final value = { + 'doubles': [0, 0.0, null], + 'nnDoubles': [0, 0.0] + }; + + roundTripNumber(Numbers.fromJson(value)); + }); + + test('does not support doubles as ints', () { + final value = { + 'ints': [3.14, 0], + }; + + expect(() => Numbers.fromJson(value), throwsCastError); + }); + }); + + test('MapKeyVariety', () { + final instance = MapKeyVariety() + ..bigIntMap = {BigInt.from(1): 1} + ..dateTimeIntMap = {DateTime.parse('2018-01-01'): 2} + ..intIntMap = {3: 3} + ..uriIntMap = {Uri.parse('https://example.com'): 4}; + + final roundTrip = + roundTripObject(instance, (j) => MapKeyVariety.fromJson(j)); + + expect(roundTrip, instance); + }); + + test('UnknownEnumValue', () { + final instance = UnknownEnumValue.fromJson({ + 'enumValue': 'nope', + 'enumIterable': ['nope'], + 'enumList': ['nope'], + 'enumSet': ['nope'], + }); + + expect(instance.enumValue, Category.notDiscoveredYet); + expect(instance.enumIterable, [Category.notDiscoveredYet]); + expect(instance.enumList, [Category.notDiscoveredYet]); + expect(instance.enumSet, [Category.notDiscoveredYet]); + }); +} diff --git a/json_serializable-3.5.2/test/integration/json_test_common.dart b/json_serializable-3.5.2/test/integration/json_test_common.dart new file mode 100644 index 000000000..295d6df85 --- /dev/null +++ b/json_serializable-3.5.2/test/integration/json_test_common.dart @@ -0,0 +1,97 @@ +// 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. + +import 'dart:collection'; + +import 'package:collection/collection.dart'; +import 'package:json_annotation/json_annotation.dart'; + +enum Category { + top, + bottom, + strange, + charmed, + up, + down, + @JsonValue('not_discovered_yet') + notDiscoveredYet +} + +enum StatusCode { + @JsonValue(200) + success, + @JsonValue(404) + notFound, + + // Intentionally using a non-int value to validate heterogeneous + // type-inference. + @JsonValue('500') + weird, + + unknown, +} + +Duration durationFromInt(int ms) => + ms == null ? null : Duration(milliseconds: ms); + +int durationToInt(Duration duration) => duration?.inMilliseconds; + +DateTime dateTimeFromEpochUs(int us) => + us == null ? null : DateTime.fromMicrosecondsSinceEpoch(us); + +int dateTimeToEpochUs(DateTime dateTime) => dateTime?.microsecondsSinceEpoch; + +bool deepEquals(a, b) => const DeepCollectionEquality().equals(a, b); + +class Platform { + final String description; + + static const Platform foo = Platform._('foo'); + static const Platform undefined = Platform._('undefined'); + + const Platform._(this.description); + + factory Platform.fromJson(String value) { + switch (value) { + case 'foo': + return foo; + case 'undefined': + return undefined; + default: + throw ArgumentError.value(value, 'value', 'Not a supported value.'); + } + } + + String toJson() => description; +} + +abstract class ItemCore { + final int price; + + ItemCore(this.price); +} + +class MyList extends ListBase { + final List _data; + + MyList(Iterable source) : _data = source.toList() ?? []; + + factory MyList.fromJson(List items) => MyList(items); + + @override + int get length => _data.length; + + @override + set length(int value) { + _data.length = value; + } + + @override + T operator [](int index) => _data[index]; + + @override + void operator []=(int index, T value) { + _data[index] = value; + } +} diff --git a/json_serializable-3.5.2/test/integration/json_test_example.dart b/json_serializable-3.5.2/test/integration/json_test_example.dart new file mode 100644 index 000000000..f23831961 --- /dev/null +++ b/json_serializable-3.5.2/test/integration/json_test_example.dart @@ -0,0 +1,196 @@ +// 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. + +// ignore_for_file: hash_and_equals +import 'dart:collection'; + +import 'package:json_annotation/json_annotation.dart'; + +import 'json_test_common.dart'; + +part 'json_test_example.g.dart'; + +@JsonSerializable() +class Person { + final String firstName, middleName, lastName; + final DateTime dateOfBirth; + @JsonKey(name: '\$house') + final Category house; + + Order order; + + MyList customOrders; + + Map houseMap; + Map categoryCounts; + + Person(this.firstName, this.lastName, this.house, + {this.middleName, this.dateOfBirth}); + + factory Person.fromJson(Map json) => _$PersonFromJson(json); + + Map toJson() => _$PersonToJson(this); + + @override + bool operator ==(Object other) => + other is Person && + firstName == other.firstName && + middleName == other.middleName && + lastName == other.lastName && + dateOfBirth == other.dateOfBirth && + house == other.house && + deepEquals(houseMap, other.houseMap); +} + +@JsonSerializable() +class Order { + /// Used to test that `disallowNullValues: true` forces `includeIfNull: false` + @JsonKey(disallowNullValue: true) + int count; + bool isRushed; + + Duration duration; + + @JsonKey(nullable: false) + final Category category; + final UnmodifiableListView items; + Platform platform; + Map altPlatforms; + + Uri homepage; + + @JsonKey( + name: 'status_code', + defaultValue: StatusCode.success, + nullable: true, + unknownEnumValue: StatusCode.unknown, + ) + StatusCode statusCode; + + @JsonKey(ignore: true) + String get platformValue => platform?.description; + + set platformValue(String value) { + throw UnimplementedError('not impld'); + } + + // Ignored getter without value set in ctor + int get price => items.fold(0, (total, item) => item.price + total); + + @JsonKey(ignore: true) + bool shouldBeCached; + + Order(this.category, [Iterable items]) + : items = UnmodifiableListView( + List.unmodifiable(items ?? const [])); + + factory Order.fromJson(Map json) => _$OrderFromJson(json); + + Map toJson() => _$OrderToJson(this); + + @override + bool operator ==(Object other) => + other is Order && + count == other.count && + isRushed == other.isRushed && + deepEquals(items, other.items) && + deepEquals(altPlatforms, other.altPlatforms); +} + +@JsonSerializable() +class Item extends ItemCore { + @JsonKey(includeIfNull: false, name: 'item-number') + int itemNumber; + List saleDates; + List rates; + + Item([int price]) : super(price); + + factory Item.fromJson(Map json) => _$ItemFromJson(json); + + Map toJson() => _$ItemToJson(this); + + @override + bool operator ==(Object other) => + other is Item && + price == other.price && + itemNumber == other.itemNumber && + deepEquals(saleDates, other.saleDates); +} + +@JsonSerializable() +class Numbers { + List ints; + List nums; + List doubles; + + @JsonKey(nullable: false) + List nnDoubles; + + @JsonKey(fromJson: durationFromInt, toJson: durationToInt) + Duration duration; + + @JsonKey(fromJson: dateTimeFromEpochUs, toJson: dateTimeToEpochUs) + DateTime date; + + Numbers(); + + factory Numbers.fromJson(Map json) => + _$NumbersFromJson(json); + + Map toJson() => _$NumbersToJson(this); + + @override + bool operator ==(Object other) => + other is Numbers && + deepEquals(ints, other.ints) && + deepEquals(nums, other.nums) && + deepEquals(doubles, other.doubles) && + deepEquals(nnDoubles, other.nnDoubles) && + deepEquals(duration, other.duration) && + deepEquals(date, other.date); +} + +@JsonSerializable() +class MapKeyVariety { + Map intIntMap; + Map uriIntMap; + Map dateTimeIntMap; + Map bigIntMap; + + MapKeyVariety(); + + factory MapKeyVariety.fromJson(Map json) => + _$MapKeyVarietyFromJson(json); + + Map toJson() => _$MapKeyVarietyToJson(this); + + @override + bool operator ==(Object other) => + other is MapKeyVariety && + deepEquals(other.intIntMap, intIntMap) && + deepEquals(other.uriIntMap, uriIntMap) && + deepEquals(other.dateTimeIntMap, dateTimeIntMap) && + deepEquals(other.bigIntMap, bigIntMap); +} + +@JsonSerializable(createToJson: false) +class UnknownEnumValue { + @JsonKey(unknownEnumValue: Category.notDiscoveredYet) + Category enumValue; + + @JsonKey(unknownEnumValue: Category.notDiscoveredYet) + Iterable enumIterable; + + @JsonKey(unknownEnumValue: Category.notDiscoveredYet) + List enumList; + + @JsonKey(unknownEnumValue: Category.notDiscoveredYet) + Set enumSet; + + UnknownEnumValue(); + + factory UnknownEnumValue.fromJson(Map json) => + _$UnknownEnumValueFromJson(json); +} diff --git a/json_serializable-3.5.2/test/integration/json_test_example.g.dart b/json_serializable-3.5.2/test/integration/json_test_example.g.dart new file mode 100644 index 000000000..4ec605cc3 --- /dev/null +++ b/json_serializable-3.5.2/test/integration/json_test_example.g.dart @@ -0,0 +1,236 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'json_test_example.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +Person _$PersonFromJson(Map json) { + return Person( + json['firstName'] as String, + json['lastName'] as String, + _$enumDecodeNullable(_$CategoryEnumMap, json[r'$house']), + middleName: json['middleName'] as String, + dateOfBirth: json['dateOfBirth'] == null + ? null + : DateTime.parse(json['dateOfBirth'] as String), + ) + ..order = json['order'] == null + ? null + : Order.fromJson(json['order'] as Map) + ..customOrders = json['customOrders'] == null + ? null + : MyList.fromJson((json['customOrders'] as List) + ?.map((e) => + e == null ? null : Order.fromJson(e as Map)) + ?.toList()) + ..houseMap = (json['houseMap'] as Map)?.map( + (k, e) => MapEntry(k, _$enumDecodeNullable(_$CategoryEnumMap, e)), + ) + ..categoryCounts = (json['categoryCounts'] as Map)?.map( + (k, e) => MapEntry(_$enumDecodeNullable(_$CategoryEnumMap, k), e as int), + ); +} + +Map _$PersonToJson(Person instance) => { + 'firstName': instance.firstName, + 'middleName': instance.middleName, + 'lastName': instance.lastName, + 'dateOfBirth': instance.dateOfBirth?.toIso8601String(), + r'$house': _$CategoryEnumMap[instance.house], + 'order': instance.order, + 'customOrders': instance.customOrders, + 'houseMap': + instance.houseMap?.map((k, e) => MapEntry(k, _$CategoryEnumMap[e])), + 'categoryCounts': instance.categoryCounts + ?.map((k, e) => MapEntry(_$CategoryEnumMap[k], e)), + }; + +T _$enumDecode( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} + +T _$enumDecodeNullable( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode(enumValues, source, unknownValue: unknownValue); +} + +const _$CategoryEnumMap = { + Category.top: 'top', + Category.bottom: 'bottom', + Category.strange: 'strange', + Category.charmed: 'charmed', + Category.up: 'up', + Category.down: 'down', + Category.notDiscoveredYet: 'not_discovered_yet', +}; + +Order _$OrderFromJson(Map json) { + $checkKeys(json, disallowNullValues: const ['count']); + return Order( + _$enumDecode(_$CategoryEnumMap, json['category']), + (json['items'] as List)?.map( + (e) => e == null ? null : Item.fromJson(e as Map)), + ) + ..count = json['count'] as int + ..isRushed = json['isRushed'] as bool + ..duration = json['duration'] == null + ? null + : Duration(microseconds: json['duration'] as int) + ..platform = json['platform'] == null + ? null + : Platform.fromJson(json['platform'] as String) + ..altPlatforms = (json['altPlatforms'] as Map)?.map( + (k, e) => MapEntry(k, e == null ? null : Platform.fromJson(e as String)), + ) + ..homepage = + json['homepage'] == null ? null : Uri.parse(json['homepage'] as String) + ..statusCode = _$enumDecodeNullable( + _$StatusCodeEnumMap, json['status_code'], + unknownValue: StatusCode.unknown) ?? + StatusCode.success; +} + +Map _$OrderToJson(Order instance) { + final val = {}; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('count', instance.count); + val['isRushed'] = instance.isRushed; + val['duration'] = instance.duration?.inMicroseconds; + val['category'] = _$CategoryEnumMap[instance.category]; + val['items'] = instance.items; + val['platform'] = instance.platform; + val['altPlatforms'] = instance.altPlatforms; + val['homepage'] = instance.homepage?.toString(); + val['status_code'] = _$StatusCodeEnumMap[instance.statusCode]; + return val; +} + +const _$StatusCodeEnumMap = { + StatusCode.success: 200, + StatusCode.notFound: 404, + StatusCode.weird: '500', + StatusCode.unknown: 'unknown', +}; + +Item _$ItemFromJson(Map json) { + return Item( + json['price'] as int, + ) + ..itemNumber = json['item-number'] as int + ..saleDates = (json['saleDates'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)) + ?.toList() + ..rates = (json['rates'] as List)?.map((e) => e as int)?.toList(); +} + +Map _$ItemToJson(Item instance) { + final val = { + 'price': instance.price, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('item-number', instance.itemNumber); + val['saleDates'] = + instance.saleDates?.map((e) => e?.toIso8601String())?.toList(); + val['rates'] = instance.rates; + return val; +} + +Numbers _$NumbersFromJson(Map json) { + return Numbers() + ..ints = (json['ints'] as List)?.map((e) => e as int)?.toList() + ..nums = (json['nums'] as List)?.map((e) => e as num)?.toList() + ..doubles = + (json['doubles'] as List)?.map((e) => (e as num)?.toDouble())?.toList() + ..nnDoubles = + (json['nnDoubles'] as List).map((e) => (e as num).toDouble()).toList() + ..duration = durationFromInt(json['duration'] as int) + ..date = dateTimeFromEpochUs(json['date'] as int); +} + +Map _$NumbersToJson(Numbers instance) => { + 'ints': instance.ints, + 'nums': instance.nums, + 'doubles': instance.doubles, + 'nnDoubles': instance.nnDoubles, + 'duration': durationToInt(instance.duration), + 'date': dateTimeToEpochUs(instance.date), + }; + +MapKeyVariety _$MapKeyVarietyFromJson(Map json) { + return MapKeyVariety() + ..intIntMap = (json['intIntMap'] as Map)?.map( + (k, e) => MapEntry(int.parse(k), e as int), + ) + ..uriIntMap = (json['uriIntMap'] as Map)?.map( + (k, e) => MapEntry(Uri.parse(k), e as int), + ) + ..dateTimeIntMap = (json['dateTimeIntMap'] as Map)?.map( + (k, e) => MapEntry(DateTime.parse(k), e as int), + ) + ..bigIntMap = (json['bigIntMap'] as Map)?.map( + (k, e) => MapEntry(BigInt.parse(k), e as int), + ); +} + +Map _$MapKeyVarietyToJson(MapKeyVariety instance) => + { + 'intIntMap': instance.intIntMap?.map((k, e) => MapEntry(k.toString(), e)), + 'uriIntMap': instance.uriIntMap?.map((k, e) => MapEntry(k.toString(), e)), + 'dateTimeIntMap': instance.dateTimeIntMap + ?.map((k, e) => MapEntry(k.toIso8601String(), e)), + 'bigIntMap': instance.bigIntMap?.map((k, e) => MapEntry(k.toString(), e)), + }; + +UnknownEnumValue _$UnknownEnumValueFromJson(Map json) { + return UnknownEnumValue() + ..enumValue = _$enumDecodeNullable(_$CategoryEnumMap, json['enumValue'], + unknownValue: Category.notDiscoveredYet) + ..enumIterable = (json['enumIterable'] as List)?.map((e) => + _$enumDecodeNullable(_$CategoryEnumMap, e, + unknownValue: Category.notDiscoveredYet)) + ..enumList = (json['enumList'] as List) + ?.map((e) => _$enumDecodeNullable(_$CategoryEnumMap, e, + unknownValue: Category.notDiscoveredYet)) + ?.toList() + ..enumSet = (json['enumSet'] as List) + ?.map((e) => _$enumDecodeNullable(_$CategoryEnumMap, e, + unknownValue: Category.notDiscoveredYet)) + ?.toSet(); +} diff --git a/json_serializable-3.5.2/test/integration/json_test_example.g_any_map.dart b/json_serializable-3.5.2/test/integration/json_test_example.g_any_map.dart new file mode 100644 index 000000000..f781d5b5c --- /dev/null +++ b/json_serializable-3.5.2/test/integration/json_test_example.g_any_map.dart @@ -0,0 +1,206 @@ +// 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. + +// ignore_for_file: hash_and_equals +import 'dart:collection'; + +import 'package:json_annotation/json_annotation.dart'; + +import 'json_test_common.dart'; + +part 'json_test_example.g_any_map.g.dart'; + +@JsonSerializable( + anyMap: true, +) +class Person { + final String firstName, middleName, lastName; + final DateTime dateOfBirth; + @JsonKey(name: '\$house') + final Category house; + + Order order; + + MyList customOrders; + + Map houseMap; + Map categoryCounts; + + Person(this.firstName, this.lastName, this.house, + {this.middleName, this.dateOfBirth}); + + factory Person.fromJson(Map json) => _$PersonFromJson(json); + + Map toJson() => _$PersonToJson(this); + + @override + bool operator ==(Object other) => + other is Person && + firstName == other.firstName && + middleName == other.middleName && + lastName == other.lastName && + dateOfBirth == other.dateOfBirth && + house == other.house && + deepEquals(houseMap, other.houseMap); +} + +@JsonSerializable( + anyMap: true, +) +class Order { + /// Used to test that `disallowNullValues: true` forces `includeIfNull: false` + @JsonKey(disallowNullValue: true) + int count; + bool isRushed; + + Duration duration; + + @JsonKey(nullable: false) + final Category category; + final UnmodifiableListView items; + Platform platform; + Map altPlatforms; + + Uri homepage; + + @JsonKey( + name: 'status_code', + defaultValue: StatusCode.success, + nullable: true, + unknownEnumValue: StatusCode.unknown, + ) + StatusCode statusCode; + + @JsonKey(ignore: true) + String get platformValue => platform?.description; + + set platformValue(String value) { + throw UnimplementedError('not impld'); + } + + // Ignored getter without value set in ctor + int get price => items.fold(0, (total, item) => item.price + total); + + @JsonKey(ignore: true) + bool shouldBeCached; + + Order(this.category, [Iterable items]) + : items = UnmodifiableListView( + List.unmodifiable(items ?? const [])); + + factory Order.fromJson(Map json) => _$OrderFromJson(json); + + Map toJson() => _$OrderToJson(this); + + @override + bool operator ==(Object other) => + other is Order && + count == other.count && + isRushed == other.isRushed && + deepEquals(items, other.items) && + deepEquals(altPlatforms, other.altPlatforms); +} + +@JsonSerializable( + anyMap: true, +) +class Item extends ItemCore { + @JsonKey(includeIfNull: false, name: 'item-number') + int itemNumber; + List saleDates; + List rates; + + Item([int price]) : super(price); + + factory Item.fromJson(Map json) => _$ItemFromJson(json); + + Map toJson() => _$ItemToJson(this); + + @override + bool operator ==(Object other) => + other is Item && + price == other.price && + itemNumber == other.itemNumber && + deepEquals(saleDates, other.saleDates); +} + +@JsonSerializable( + anyMap: true, +) +class Numbers { + List ints; + List nums; + List doubles; + + @JsonKey(nullable: false) + List nnDoubles; + + @JsonKey(fromJson: durationFromInt, toJson: durationToInt) + Duration duration; + + @JsonKey(fromJson: dateTimeFromEpochUs, toJson: dateTimeToEpochUs) + DateTime date; + + Numbers(); + + factory Numbers.fromJson(Map json) => + _$NumbersFromJson(json); + + Map toJson() => _$NumbersToJson(this); + + @override + bool operator ==(Object other) => + other is Numbers && + deepEquals(ints, other.ints) && + deepEquals(nums, other.nums) && + deepEquals(doubles, other.doubles) && + deepEquals(nnDoubles, other.nnDoubles) && + deepEquals(duration, other.duration) && + deepEquals(date, other.date); +} + +@JsonSerializable( + anyMap: true, +) +class MapKeyVariety { + Map intIntMap; + Map uriIntMap; + Map dateTimeIntMap; + Map bigIntMap; + + MapKeyVariety(); + + factory MapKeyVariety.fromJson(Map json) => + _$MapKeyVarietyFromJson(json); + + Map toJson() => _$MapKeyVarietyToJson(this); + + @override + bool operator ==(Object other) => + other is MapKeyVariety && + deepEquals(other.intIntMap, intIntMap) && + deepEquals(other.uriIntMap, uriIntMap) && + deepEquals(other.dateTimeIntMap, dateTimeIntMap) && + deepEquals(other.bigIntMap, bigIntMap); +} + +@JsonSerializable(anyMap: true, createToJson: false) +class UnknownEnumValue { + @JsonKey(unknownEnumValue: Category.notDiscoveredYet) + Category enumValue; + + @JsonKey(unknownEnumValue: Category.notDiscoveredYet) + Iterable enumIterable; + + @JsonKey(unknownEnumValue: Category.notDiscoveredYet) + List enumList; + + @JsonKey(unknownEnumValue: Category.notDiscoveredYet) + Set enumSet; + + UnknownEnumValue(); + + factory UnknownEnumValue.fromJson(Map json) => + _$UnknownEnumValueFromJson(json); +} diff --git a/json_serializable-3.5.2/test/integration/json_test_example.g_any_map.g.dart b/json_serializable-3.5.2/test/integration/json_test_example.g_any_map.g.dart new file mode 100644 index 000000000..e4f24df48 --- /dev/null +++ b/json_serializable-3.5.2/test/integration/json_test_example.g_any_map.g.dart @@ -0,0 +1,246 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'json_test_example.g_any_map.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +Person _$PersonFromJson(Map json) { + return Person( + json['firstName'] as String, + json['lastName'] as String, + _$enumDecodeNullable(_$CategoryEnumMap, json[r'$house']), + middleName: json['middleName'] as String, + dateOfBirth: json['dateOfBirth'] == null + ? null + : DateTime.parse(json['dateOfBirth'] as String), + ) + ..order = json['order'] == null + ? null + : Order.fromJson((json['order'] as Map)?.map( + (k, e) => MapEntry(k as String, e), + )) + ..customOrders = json['customOrders'] == null + ? null + : MyList.fromJson((json['customOrders'] as List) + ?.map((e) => e == null + ? null + : Order.fromJson((e as Map)?.map( + (k, e) => MapEntry(k as String, e), + ))) + ?.toList()) + ..houseMap = (json['houseMap'] as Map)?.map( + (k, e) => + MapEntry(k as String, _$enumDecodeNullable(_$CategoryEnumMap, e)), + ) + ..categoryCounts = (json['categoryCounts'] as Map)?.map( + (k, e) => MapEntry(_$enumDecodeNullable(_$CategoryEnumMap, k), e as int), + ); +} + +Map _$PersonToJson(Person instance) => { + 'firstName': instance.firstName, + 'middleName': instance.middleName, + 'lastName': instance.lastName, + 'dateOfBirth': instance.dateOfBirth?.toIso8601String(), + r'$house': _$CategoryEnumMap[instance.house], + 'order': instance.order, + 'customOrders': instance.customOrders, + 'houseMap': + instance.houseMap?.map((k, e) => MapEntry(k, _$CategoryEnumMap[e])), + 'categoryCounts': instance.categoryCounts + ?.map((k, e) => MapEntry(_$CategoryEnumMap[k], e)), + }; + +T _$enumDecode( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} + +T _$enumDecodeNullable( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode(enumValues, source, unknownValue: unknownValue); +} + +const _$CategoryEnumMap = { + Category.top: 'top', + Category.bottom: 'bottom', + Category.strange: 'strange', + Category.charmed: 'charmed', + Category.up: 'up', + Category.down: 'down', + Category.notDiscoveredYet: 'not_discovered_yet', +}; + +Order _$OrderFromJson(Map json) { + $checkKeys(json, disallowNullValues: const ['count']); + return Order( + _$enumDecode(_$CategoryEnumMap, json['category']), + (json['items'] as List)?.map((e) => e == null + ? null + : Item.fromJson((e as Map)?.map( + (k, e) => MapEntry(k as String, e), + ))), + ) + ..count = json['count'] as int + ..isRushed = json['isRushed'] as bool + ..duration = json['duration'] == null + ? null + : Duration(microseconds: json['duration'] as int) + ..platform = json['platform'] == null + ? null + : Platform.fromJson(json['platform'] as String) + ..altPlatforms = (json['altPlatforms'] as Map)?.map( + (k, e) => MapEntry( + k as String, e == null ? null : Platform.fromJson(e as String)), + ) + ..homepage = + json['homepage'] == null ? null : Uri.parse(json['homepage'] as String) + ..statusCode = _$enumDecodeNullable( + _$StatusCodeEnumMap, json['status_code'], + unknownValue: StatusCode.unknown) ?? + StatusCode.success; +} + +Map _$OrderToJson(Order instance) { + final val = {}; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('count', instance.count); + val['isRushed'] = instance.isRushed; + val['duration'] = instance.duration?.inMicroseconds; + val['category'] = _$CategoryEnumMap[instance.category]; + val['items'] = instance.items; + val['platform'] = instance.platform; + val['altPlatforms'] = instance.altPlatforms; + val['homepage'] = instance.homepage?.toString(); + val['status_code'] = _$StatusCodeEnumMap[instance.statusCode]; + return val; +} + +const _$StatusCodeEnumMap = { + StatusCode.success: 200, + StatusCode.notFound: 404, + StatusCode.weird: '500', + StatusCode.unknown: 'unknown', +}; + +Item _$ItemFromJson(Map json) { + return Item( + json['price'] as int, + ) + ..itemNumber = json['item-number'] as int + ..saleDates = (json['saleDates'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)) + ?.toList() + ..rates = (json['rates'] as List)?.map((e) => e as int)?.toList(); +} + +Map _$ItemToJson(Item instance) { + final val = { + 'price': instance.price, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('item-number', instance.itemNumber); + val['saleDates'] = + instance.saleDates?.map((e) => e?.toIso8601String())?.toList(); + val['rates'] = instance.rates; + return val; +} + +Numbers _$NumbersFromJson(Map json) { + return Numbers() + ..ints = (json['ints'] as List)?.map((e) => e as int)?.toList() + ..nums = (json['nums'] as List)?.map((e) => e as num)?.toList() + ..doubles = + (json['doubles'] as List)?.map((e) => (e as num)?.toDouble())?.toList() + ..nnDoubles = + (json['nnDoubles'] as List).map((e) => (e as num).toDouble()).toList() + ..duration = durationFromInt(json['duration'] as int) + ..date = dateTimeFromEpochUs(json['date'] as int); +} + +Map _$NumbersToJson(Numbers instance) => { + 'ints': instance.ints, + 'nums': instance.nums, + 'doubles': instance.doubles, + 'nnDoubles': instance.nnDoubles, + 'duration': durationToInt(instance.duration), + 'date': dateTimeToEpochUs(instance.date), + }; + +MapKeyVariety _$MapKeyVarietyFromJson(Map json) { + return MapKeyVariety() + ..intIntMap = (json['intIntMap'] as Map)?.map( + (k, e) => MapEntry(int.parse(k as String), e as int), + ) + ..uriIntMap = (json['uriIntMap'] as Map)?.map( + (k, e) => MapEntry(Uri.parse(k as String), e as int), + ) + ..dateTimeIntMap = (json['dateTimeIntMap'] as Map)?.map( + (k, e) => MapEntry(DateTime.parse(k as String), e as int), + ) + ..bigIntMap = (json['bigIntMap'] as Map)?.map( + (k, e) => MapEntry(BigInt.parse(k as String), e as int), + ); +} + +Map _$MapKeyVarietyToJson(MapKeyVariety instance) => + { + 'intIntMap': instance.intIntMap?.map((k, e) => MapEntry(k.toString(), e)), + 'uriIntMap': instance.uriIntMap?.map((k, e) => MapEntry(k.toString(), e)), + 'dateTimeIntMap': instance.dateTimeIntMap + ?.map((k, e) => MapEntry(k.toIso8601String(), e)), + 'bigIntMap': instance.bigIntMap?.map((k, e) => MapEntry(k.toString(), e)), + }; + +UnknownEnumValue _$UnknownEnumValueFromJson(Map json) { + return UnknownEnumValue() + ..enumValue = _$enumDecodeNullable(_$CategoryEnumMap, json['enumValue'], + unknownValue: Category.notDiscoveredYet) + ..enumIterable = (json['enumIterable'] as List)?.map((e) => + _$enumDecodeNullable(_$CategoryEnumMap, e, + unknownValue: Category.notDiscoveredYet)) + ..enumList = (json['enumList'] as List) + ?.map((e) => _$enumDecodeNullable(_$CategoryEnumMap, e, + unknownValue: Category.notDiscoveredYet)) + ?.toList() + ..enumSet = (json['enumSet'] as List) + ?.map((e) => _$enumDecodeNullable(_$CategoryEnumMap, e, + unknownValue: Category.notDiscoveredYet)) + ?.toSet(); +} diff --git a/json_serializable-3.5.2/test/integration/json_test_example.g_non_nullable.dart b/json_serializable-3.5.2/test/integration/json_test_example.g_non_nullable.dart new file mode 100644 index 000000000..cb9928180 --- /dev/null +++ b/json_serializable-3.5.2/test/integration/json_test_example.g_non_nullable.dart @@ -0,0 +1,206 @@ +// 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. + +// ignore_for_file: hash_and_equals +import 'dart:collection'; + +import 'package:json_annotation/json_annotation.dart'; + +import 'json_test_common.dart'; + +part 'json_test_example.g_non_nullable.g.dart'; + +@JsonSerializable( + nullable: false, +) +class Person { + final String firstName, middleName, lastName; + final DateTime dateOfBirth; + @JsonKey(name: '\$house') + final Category house; + + Order order; + + MyList customOrders; + + Map houseMap; + Map categoryCounts; + + Person(this.firstName, this.lastName, this.house, + {this.middleName, this.dateOfBirth}); + + factory Person.fromJson(Map json) => _$PersonFromJson(json); + + Map toJson() => _$PersonToJson(this); + + @override + bool operator ==(Object other) => + other is Person && + firstName == other.firstName && + middleName == other.middleName && + lastName == other.lastName && + dateOfBirth == other.dateOfBirth && + house == other.house && + deepEquals(houseMap, other.houseMap); +} + +@JsonSerializable( + nullable: false, +) +class Order { + /// Used to test that `disallowNullValues: true` forces `includeIfNull: false` + @JsonKey(disallowNullValue: true) + int count; + bool isRushed; + + Duration duration; + + @JsonKey(nullable: false) + final Category category; + final UnmodifiableListView items; + Platform platform; + Map altPlatforms; + + Uri homepage; + + @JsonKey( + name: 'status_code', + defaultValue: StatusCode.success, + nullable: true, + unknownEnumValue: StatusCode.unknown, + ) + StatusCode statusCode; + + @JsonKey(ignore: true) + String get platformValue => platform?.description; + + set platformValue(String value) { + throw UnimplementedError('not impld'); + } + + // Ignored getter without value set in ctor + int get price => items.fold(0, (total, item) => item.price + total); + + @JsonKey(ignore: true) + bool shouldBeCached; + + Order(this.category, [Iterable items]) + : items = UnmodifiableListView( + List.unmodifiable(items ?? const [])); + + factory Order.fromJson(Map json) => _$OrderFromJson(json); + + Map toJson() => _$OrderToJson(this); + + @override + bool operator ==(Object other) => + other is Order && + count == other.count && + isRushed == other.isRushed && + deepEquals(items, other.items) && + deepEquals(altPlatforms, other.altPlatforms); +} + +@JsonSerializable( + nullable: false, +) +class Item extends ItemCore { + @JsonKey(includeIfNull: false, name: 'item-number') + int itemNumber; + List saleDates; + List rates; + + Item([int price]) : super(price); + + factory Item.fromJson(Map json) => _$ItemFromJson(json); + + Map toJson() => _$ItemToJson(this); + + @override + bool operator ==(Object other) => + other is Item && + price == other.price && + itemNumber == other.itemNumber && + deepEquals(saleDates, other.saleDates); +} + +@JsonSerializable( + nullable: false, +) +class Numbers { + List ints; + List nums; + List doubles; + + @JsonKey(nullable: false) + List nnDoubles; + + @JsonKey(fromJson: durationFromInt, toJson: durationToInt) + Duration duration; + + @JsonKey(fromJson: dateTimeFromEpochUs, toJson: dateTimeToEpochUs) + DateTime date; + + Numbers(); + + factory Numbers.fromJson(Map json) => + _$NumbersFromJson(json); + + Map toJson() => _$NumbersToJson(this); + + @override + bool operator ==(Object other) => + other is Numbers && + deepEquals(ints, other.ints) && + deepEquals(nums, other.nums) && + deepEquals(doubles, other.doubles) && + deepEquals(nnDoubles, other.nnDoubles) && + deepEquals(duration, other.duration) && + deepEquals(date, other.date); +} + +@JsonSerializable( + nullable: false, +) +class MapKeyVariety { + Map intIntMap; + Map uriIntMap; + Map dateTimeIntMap; + Map bigIntMap; + + MapKeyVariety(); + + factory MapKeyVariety.fromJson(Map json) => + _$MapKeyVarietyFromJson(json); + + Map toJson() => _$MapKeyVarietyToJson(this); + + @override + bool operator ==(Object other) => + other is MapKeyVariety && + deepEquals(other.intIntMap, intIntMap) && + deepEquals(other.uriIntMap, uriIntMap) && + deepEquals(other.dateTimeIntMap, dateTimeIntMap) && + deepEquals(other.bigIntMap, bigIntMap); +} + +@JsonSerializable(nullable: false, createToJson: false) +class UnknownEnumValue { + @JsonKey(unknownEnumValue: Category.notDiscoveredYet) + Category enumValue; + + @JsonKey(unknownEnumValue: Category.notDiscoveredYet) + Iterable enumIterable; + + @JsonKey(unknownEnumValue: Category.notDiscoveredYet) + List enumList; + + @JsonKey(unknownEnumValue: Category.notDiscoveredYet) + Set enumSet; + + UnknownEnumValue(); + + factory UnknownEnumValue.fromJson(Map json) => + _$UnknownEnumValueFromJson(json); +} diff --git a/json_serializable-3.5.2/test/integration/json_test_example.g_non_nullable.g.dart b/json_serializable-3.5.2/test/integration/json_test_example.g_non_nullable.g.dart new file mode 100644 index 000000000..6c0e324d6 --- /dev/null +++ b/json_serializable-3.5.2/test/integration/json_test_example.g_non_nullable.g.dart @@ -0,0 +1,203 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'json_test_example.g_non_nullable.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +Person _$PersonFromJson(Map json) { + return Person( + json['firstName'] as String, + json['lastName'] as String, + _$enumDecode(_$CategoryEnumMap, json[r'$house']), + middleName: json['middleName'] as String, + dateOfBirth: DateTime.parse(json['dateOfBirth'] as String), + ) + ..order = Order.fromJson(json['order'] as Map) + ..customOrders = MyList.fromJson((json['customOrders'] as List) + .map((e) => Order.fromJson(e as Map)) + .toList()) + ..houseMap = (json['houseMap'] as Map).map( + (k, e) => MapEntry(k, _$enumDecode(_$CategoryEnumMap, e)), + ) + ..categoryCounts = (json['categoryCounts'] as Map).map( + (k, e) => MapEntry(_$enumDecode(_$CategoryEnumMap, k), e as int), + ); +} + +Map _$PersonToJson(Person instance) => { + 'firstName': instance.firstName, + 'middleName': instance.middleName, + 'lastName': instance.lastName, + 'dateOfBirth': instance.dateOfBirth.toIso8601String(), + r'$house': _$CategoryEnumMap[instance.house], + 'order': instance.order, + 'customOrders': instance.customOrders, + 'houseMap': + instance.houseMap.map((k, e) => MapEntry(k, _$CategoryEnumMap[e])), + 'categoryCounts': instance.categoryCounts + .map((k, e) => MapEntry(_$CategoryEnumMap[k], e)), + }; + +T _$enumDecode( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} + +const _$CategoryEnumMap = { + Category.top: 'top', + Category.bottom: 'bottom', + Category.strange: 'strange', + Category.charmed: 'charmed', + Category.up: 'up', + Category.down: 'down', + Category.notDiscoveredYet: 'not_discovered_yet', +}; + +Order _$OrderFromJson(Map json) { + $checkKeys(json, disallowNullValues: const ['count']); + return Order( + _$enumDecode(_$CategoryEnumMap, json['category']), + (json['items'] as List) + .map((e) => Item.fromJson(e as Map)), + ) + ..count = json['count'] as int + ..isRushed = json['isRushed'] as bool + ..duration = Duration(microseconds: json['duration'] as int) + ..platform = Platform.fromJson(json['platform'] as String) + ..altPlatforms = (json['altPlatforms'] as Map).map( + (k, e) => MapEntry(k, Platform.fromJson(e as String)), + ) + ..homepage = Uri.parse(json['homepage'] as String) + ..statusCode = _$enumDecodeNullable( + _$StatusCodeEnumMap, json['status_code'], + unknownValue: StatusCode.unknown) ?? + StatusCode.success; +} + +Map _$OrderToJson(Order instance) => { + 'count': instance.count, + 'isRushed': instance.isRushed, + 'duration': instance.duration.inMicroseconds, + 'category': _$CategoryEnumMap[instance.category], + 'items': instance.items, + 'platform': instance.platform, + 'altPlatforms': instance.altPlatforms, + 'homepage': instance.homepage.toString(), + 'status_code': _$StatusCodeEnumMap[instance.statusCode], + }; + +T _$enumDecodeNullable( + Map enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode(enumValues, source, unknownValue: unknownValue); +} + +const _$StatusCodeEnumMap = { + StatusCode.success: 200, + StatusCode.notFound: 404, + StatusCode.weird: '500', + StatusCode.unknown: 'unknown', +}; + +Item _$ItemFromJson(Map json) { + return Item( + json['price'] as int, + ) + ..itemNumber = json['item-number'] as int + ..saleDates = (json['saleDates'] as List) + .map((e) => DateTime.parse(e as String)) + .toList() + ..rates = (json['rates'] as List).map((e) => e as int).toList(); +} + +Map _$ItemToJson(Item instance) => { + 'price': instance.price, + 'item-number': instance.itemNumber, + 'saleDates': instance.saleDates.map((e) => e.toIso8601String()).toList(), + 'rates': instance.rates, + }; + +Numbers _$NumbersFromJson(Map json) { + return Numbers() + ..ints = (json['ints'] as List).map((e) => e as int).toList() + ..nums = (json['nums'] as List).map((e) => e as num).toList() + ..doubles = + (json['doubles'] as List).map((e) => (e as num).toDouble()).toList() + ..nnDoubles = + (json['nnDoubles'] as List).map((e) => (e as num).toDouble()).toList() + ..duration = durationFromInt(json['duration'] as int) + ..date = dateTimeFromEpochUs(json['date'] as int); +} + +Map _$NumbersToJson(Numbers instance) => { + 'ints': instance.ints, + 'nums': instance.nums, + 'doubles': instance.doubles, + 'nnDoubles': instance.nnDoubles, + 'duration': durationToInt(instance.duration), + 'date': dateTimeToEpochUs(instance.date), + }; + +MapKeyVariety _$MapKeyVarietyFromJson(Map json) { + return MapKeyVariety() + ..intIntMap = (json['intIntMap'] as Map).map( + (k, e) => MapEntry(int.parse(k), e as int), + ) + ..uriIntMap = (json['uriIntMap'] as Map).map( + (k, e) => MapEntry(Uri.parse(k), e as int), + ) + ..dateTimeIntMap = (json['dateTimeIntMap'] as Map).map( + (k, e) => MapEntry(DateTime.parse(k), e as int), + ) + ..bigIntMap = (json['bigIntMap'] as Map).map( + (k, e) => MapEntry(BigInt.parse(k), e as int), + ); +} + +Map _$MapKeyVarietyToJson(MapKeyVariety instance) => + { + 'intIntMap': instance.intIntMap.map((k, e) => MapEntry(k.toString(), e)), + 'uriIntMap': instance.uriIntMap.map((k, e) => MapEntry(k.toString(), e)), + 'dateTimeIntMap': instance.dateTimeIntMap + .map((k, e) => MapEntry(k.toIso8601String(), e)), + 'bigIntMap': instance.bigIntMap.map((k, e) => MapEntry(k.toString(), e)), + }; + +UnknownEnumValue _$UnknownEnumValueFromJson(Map json) { + return UnknownEnumValue() + ..enumValue = _$enumDecode(_$CategoryEnumMap, json['enumValue'], + unknownValue: Category.notDiscoveredYet) + ..enumIterable = (json['enumIterable'] as List).map((e) => _$enumDecode( + _$CategoryEnumMap, e, unknownValue: Category.notDiscoveredYet)) + ..enumList = (json['enumList'] as List) + .map((e) => _$enumDecode(_$CategoryEnumMap, e, + unknownValue: Category.notDiscoveredYet)) + .toList() + ..enumSet = (json['enumSet'] as List) + .map((e) => _$enumDecode(_$CategoryEnumMap, e, + unknownValue: Category.notDiscoveredYet)) + .toSet(); +} diff --git a/json_serializable-3.5.2/test/json_serializable_test.dart b/json_serializable-3.5.2/test/json_serializable_test.dart new file mode 100644 index 000000000..c834eb220 --- /dev/null +++ b/json_serializable-3.5.2/test/json_serializable_test.dart @@ -0,0 +1,117 @@ +// Copyright (c) 2015, 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. + +@TestOn('vm') +import 'package:json_serializable/json_serializable.dart'; +import 'package:path/path.dart' as p; +import 'package:source_gen_test/source_gen_test.dart'; +import 'package:test/test.dart'; + +Future main() async { + initializeBuildLogTracking(); + final reader = await initializeLibraryReaderForDirectory( + p.join('test', 'src'), + '_json_serializable_test_input.dart', + ); + + testAnnotatedElements( + reader, + JsonSerializableGenerator(), + expectedAnnotatedTests: _expectedAnnotatedTests, + ); +} + +const _expectedAnnotatedTests = [ + 'annotatedMethod', + 'BadFromFuncReturnType', + 'BadNoArgs', + 'BadOneNamed', + 'BadToFuncReturnType', + 'BadTwoRequiredPositional', + 'DefaultDoubleConstants', + 'DefaultWithConstObject', + 'DefaultWithDisallowNullRequiredClass', + 'DefaultWithFunction', + 'DefaultWithNestedEnum', + 'DefaultWithNonNullableClass', + 'DefaultWithNonNullableField', + 'DefaultWithSymbol', + 'DefaultWithToJsonClass', + 'DefaultWithType', + 'DupeKeys', + 'DynamicConvertMethods', + 'FieldNamerKebab', + 'FieldNamerNone', + 'FieldNamerPascal', + 'FieldNamerSnake', + 'FieldWithFromJsonCtorAndTypeParams', + 'FinalFields', + 'FinalFieldsNotSetInCtor', + 'FromDynamicCollection', + 'GeneralTestClass1', + 'GeneralTestClass2', + 'GenericArgumentFactoriesFlagWithoutGenericType', + 'GenericClass', + 'IgnoredFieldClass', + 'IgnoredFieldCtorClass', + 'IgnoreUnannotated', + 'IncludeIfNullDisallowNullClass', + 'IncludeIfNullOverride', + 'InvalidChildClassFromJson', + 'InvalidChildClassFromJson2', + 'InvalidChildClassFromJson3', + 'InvalidFromFunc2Args', + 'InvalidToFunc2Args', + 'Issue713', + 'JsonConverterCtorParams', + 'JsonConverterDuplicateAnnotations', + 'JsonConverterNamedCtor', + 'JsonConverterOnGetter', + 'JsonConverterWithBadTypeArg', + 'JsonConvertOnField', + 'JsonValueValid', + 'JsonValueWithBool', + 'JustSetter', + 'JustSetterNoFromJson', + 'JustSetterNoToJson', + 'KeyDupesField', + 'MapKeyVariety', + 'NoCtorClass', + 'NoDeserializeBadKey', + 'NoDeserializeFieldType', + 'NoSerializeBadKey', + 'NoSerializeFieldType', + 'ObjectConvertMethods', + 'OkayOneNormalOptionalNamed', + 'OkayOneNormalOptionalPositional', + 'OkayOnlyOptionalPositional', + 'OnlyStaticMembers', + 'OverrideGetterExampleI613', + 'PrivateFieldCtorClass', + 'PropInMixinI448Regression', + 'SetSupport', + 'SubclassedJsonKey', + 'SubType', + 'SubTypeWithAnnotatedFieldOverrideExtends', + 'SubTypeWithAnnotatedFieldOverrideExtendsWithOverrides', + 'SubTypeWithAnnotatedFieldOverrideImplements', + 'theAnswer', + 'ToJsonNullableFalseIncludeIfNullFalse', + 'TypedConvertMethods', + 'UnknownEnumValue', + 'UnknownEnumValueNotEnumValue', + 'UnknownEnumValueListWrongEnumType', + 'UnknownEnumValueListWrongType', + 'UnknownEnumValueWrongEnumType', + 'UnknownEnumValueNotEnumField', + 'UnsupportedDateTimeField', + 'UnsupportedDurationField', + 'UnsupportedListField', + 'UnsupportedMapField', + 'UnsupportedSetField', + 'UnsupportedUriField', + 'ValidToFromFuncClassStatic', + 'WithANonCtorGetter', + 'WithANonCtorGetterChecked', +]; diff --git a/json_serializable-3.5.2/test/kitchen_sink/json_converters.dart b/json_serializable-3.5.2/test/kitchen_sink/json_converters.dart new file mode 100644 index 000000000..f4b24d8b1 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/json_converters.dart @@ -0,0 +1,67 @@ +// 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. + +import 'package:json_annotation/json_annotation.dart'; + +class GenericConverter implements JsonConverter> { + const GenericConverter(); + + @override + T fromJson(Map json) => null; + + @override + Map toJson(T object) => {}; +} + +class TrivialNumber { + final int value; + + TrivialNumber(this.value); +} + +class TrivialNumberConverter implements JsonConverter { + static const instance = TrivialNumberConverter(); + + const TrivialNumberConverter(); + + @override + TrivialNumber fromJson(int json) => TrivialNumber(json); + + @override + int toJson(TrivialNumber object) => object?.value; +} + +class BigIntStringConverter implements JsonConverter { + const BigIntStringConverter(); + + @override + BigInt fromJson(String json) => json == null ? null : BigInt.parse(json); + + @override + String toJson(BigInt object) => object?.toString(); +} + +const durationConverter = DurationMillisecondConverter(); + +class DurationMillisecondConverter implements JsonConverter { + const DurationMillisecondConverter(); + + @override + Duration fromJson(int json) => + json == null ? null : Duration(milliseconds: json); + + @override + int toJson(Duration object) => object?.inMilliseconds; +} + +class EpochDateTimeConverter implements JsonConverter { + const EpochDateTimeConverter(); + + @override + DateTime fromJson(int json) => + json == null ? null : DateTime.fromMillisecondsSinceEpoch(json); + + @override + int toJson(DateTime object) => object?.millisecondsSinceEpoch; +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.dart new file mode 100644 index 000000000..aeaa57dde --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.dart @@ -0,0 +1,193 @@ +// 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. + +// ignore_for_file: annotate_overrides, hash_and_equals +import 'package:json_annotation/json_annotation.dart'; + +import 'json_converters.dart'; +import 'kitchen_sink_interface.dart' as k; +import 'simple_object.dart'; +import 'strict_keys_object.dart'; + +part 'kitchen_sink.g.dart'; + +// NOTE: these methods are replaced in the `non_nullable` cases to return +// non-null values. +List _defaultList() => null; +Set _defaultSet() => null; +Map _defaultMap() => null; +SimpleObject _defaultSimpleObject() => null; +StrictKeysObject _defaultStrictKeysObject() => null; + +const k.KitchenSinkFactory factory = _Factory(); + +class _Factory implements k.KitchenSinkFactory { + const _Factory(); + + String get description => '--defaults--'; + bool get anyMap => false; + bool get checked => false; + bool get nullable => true; + bool get excludeNull => false; + bool get explicitToJson => false; + + k.KitchenSink ctor({ + int ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) => + KitchenSink( + ctorValidatedNo42: ctorValidatedNo42, + iterable: iterable, + dynamicIterable: dynamicIterable, + objectIterable: objectIterable, + intIterable: intIterable, + dateTimeIterable: dateTimeIterable, + ); + + k.KitchenSink fromJson(Map json) => + KitchenSink.fromJson(json); + + k.JsonConverterTestClass jsonConverterCtor() => JsonConverterTestClass(); + + k.JsonConverterTestClass jsonConverterFromJson(Map json) => + JsonConverterTestClass.fromJson(json); +} + +@JsonSerializable() +class KitchenSink implements k.KitchenSink { + // NOTE: exposing these as Iterable, but storing the values as List + // to make the equality test work trivially. + final Iterable _iterable; + final Iterable _dynamicIterable; + final Iterable _objectIterable; + final Iterable _intIterable; + final Iterable _dateTimeIterable; + + @JsonKey(name: 'no-42') + final int ctorValidatedNo42; + + KitchenSink({ + this.ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) : _iterable = iterable?.toList() ?? _defaultList(), + _dynamicIterable = dynamicIterable?.toList() ?? _defaultList(), + _objectIterable = objectIterable?.toList() ?? _defaultList(), + _intIterable = intIterable?.toList() ?? _defaultList(), + _dateTimeIterable = dateTimeIterable?.toList() ?? _defaultList() { + if (ctorValidatedNo42 == 42) { + throw ArgumentError.value( + 42, 'ctorValidatedNo42', 'The value `42` is not allowed.'); + } + } + + factory KitchenSink.fromJson(Map json) => + _$KitchenSinkFromJson(json); + + Map toJson() => _$KitchenSinkToJson(this); + + DateTime dateTime; + + BigInt bigInt; + + Iterable get iterable => _iterable; + Iterable get dynamicIterable => _dynamicIterable; + Iterable get objectIterable => _objectIterable; + Iterable get intIterable => _intIterable; + + Set set = _defaultSet(); + Set dynamicSet = _defaultSet(); + Set objectSet = _defaultSet(); + Set intSet = _defaultSet(); + Set dateTimeSet = _defaultSet(); + + // Added a one-off annotation on a property (not a field) + @JsonKey(name: 'datetime-iterable') + Iterable get dateTimeIterable => _dateTimeIterable; + + List list = _defaultList(); + List dynamicList = _defaultList(); + List objectList = _defaultList(); + List intList = _defaultList(); + List dateTimeList = _defaultList(); + + Map map = _defaultMap(); + Map stringStringMap = _defaultMap(); + Map dynamicIntMap = _defaultMap(); + Map objectDateTimeMap = _defaultMap(); + + List>>>> crazyComplex = + _defaultList(); + + // Handle fields with names that collide with helper names + Map val = _defaultMap(); + bool writeNotNull; + @JsonKey(name: r'$string') + String string; + + SimpleObject simpleObject = _defaultSimpleObject(); + + StrictKeysObject strictKeysObject = _defaultStrictKeysObject(); + + int _validatedPropertyNo42; + int get validatedPropertyNo42 => _validatedPropertyNo42; + + set validatedPropertyNo42(int value) { + if (value == 42) { + throw StateError('Cannot be 42!'); + } + _validatedPropertyNo42 = value; + } + + bool operator ==(Object other) => k.sinkEquals(this, other); +} + +@JsonSerializable() +// referencing a top-level field should work +@durationConverter +// referencing via a const constructor should work +@BigIntStringConverter() +@TrivialNumberConverter.instance +@EpochDateTimeConverter() +class JsonConverterTestClass implements k.JsonConverterTestClass { + JsonConverterTestClass(); + + factory JsonConverterTestClass.fromJson(Map json) => + _$JsonConverterTestClassFromJson(json); + + Map toJson() => _$JsonConverterTestClassToJson(this); + + Duration duration; + List durationList; + + BigInt bigInt; + Map bigIntMap; + + TrivialNumber numberSilly; + Set numberSillySet; + + DateTime dateTime; +} + +@JsonSerializable() +@GenericConverter() +class JsonConverterGeneric { + S item; + List itemList; + Map itemMap; + + JsonConverterGeneric(); + + factory JsonConverterGeneric.fromJson(Map json) => + _$JsonConverterGenericFromJson(json); + + Map toJson() => _$JsonConverterGenericToJson(this); +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.factories.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.factories.dart new file mode 100644 index 000000000..8248cdc8a --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.factories.dart @@ -0,0 +1,21 @@ +import 'kitchen_sink.dart' as normal; +import 'kitchen_sink.g_any_map.dart' as any_map; +import 'kitchen_sink.g_any_map__checked__non_nullable.dart' + as any_map__checked__non_nullable; +import 'kitchen_sink.g_any_map__non_nullable.dart' as any_map__non_nullable; +import 'kitchen_sink.g_exclude_null.dart' as exclude_null; +import 'kitchen_sink.g_exclude_null__non_nullable.dart' + as exclude_null__non_nullable; +import 'kitchen_sink.g_explicit_to_json.dart' as explicit_to_json; +import 'kitchen_sink.g_non_nullable.dart' as non_nullable; + +const factories = [ + normal.factory, + any_map.factory, + any_map__checked__non_nullable.factory, + any_map__non_nullable.factory, + exclude_null.factory, + exclude_null__non_nullable.factory, + explicit_to_json.factory, + non_nullable.factory, +]; diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g.dart new file mode 100644 index 000000000..a6f1555ca --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g.dart @@ -0,0 +1,187 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'kitchen_sink.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +KitchenSink _$KitchenSinkFromJson(Map json) { + return KitchenSink( + ctorValidatedNo42: json['no-42'] as int, + iterable: json['iterable'] as List, + dynamicIterable: json['dynamicIterable'] as List, + objectIterable: json['objectIterable'] as List, + intIterable: (json['intIterable'] as List)?.map((e) => e as int), + dateTimeIterable: (json['datetime-iterable'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)), + ) + ..dateTime = json['dateTime'] == null + ? null + : DateTime.parse(json['dateTime'] as String) + ..bigInt = + json['bigInt'] == null ? null : BigInt.parse(json['bigInt'] as String) + ..set = (json['set'] as List)?.toSet() + ..dynamicSet = (json['dynamicSet'] as List)?.toSet() + ..objectSet = (json['objectSet'] as List)?.toSet() + ..intSet = (json['intSet'] as List)?.map((e) => e as int)?.toSet() + ..dateTimeSet = (json['dateTimeSet'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)) + ?.toSet() + ..list = json['list'] as List + ..dynamicList = json['dynamicList'] as List + ..objectList = json['objectList'] as List + ..intList = (json['intList'] as List)?.map((e) => e as int)?.toList() + ..dateTimeList = (json['dateTimeList'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)) + ?.toList() + ..map = json['map'] as Map + ..stringStringMap = (json['stringStringMap'] as Map)?.map( + (k, e) => MapEntry(k, e as String), + ) + ..dynamicIntMap = (json['dynamicIntMap'] as Map)?.map( + (k, e) => MapEntry(k, e as int), + ) + ..objectDateTimeMap = + (json['objectDateTimeMap'] as Map)?.map( + (k, e) => MapEntry(k, e == null ? null : DateTime.parse(e as String)), + ) + ..crazyComplex = (json['crazyComplex'] as List) + ?.map((e) => (e as Map)?.map( + (k, e) => MapEntry( + k, + (e as Map)?.map( + (k, e) => MapEntry( + k, + (e as List) + ?.map((e) => (e as List) + ?.map((e) => e == null + ? null + : DateTime.parse(e as String)) + ?.toList()) + ?.toList()), + )), + )) + ?.toList() + ..val = (json['val'] as Map)?.map( + (k, e) => MapEntry(k, e as bool), + ) + ..writeNotNull = json['writeNotNull'] as bool + ..string = json[r'$string'] as String + ..simpleObject = json['simpleObject'] == null + ? null + : SimpleObject.fromJson(json['simpleObject'] as Map) + ..strictKeysObject = json['strictKeysObject'] == null + ? null + : StrictKeysObject.fromJson( + json['strictKeysObject'] as Map) + ..validatedPropertyNo42 = json['validatedPropertyNo42'] as int; +} + +Map _$KitchenSinkToJson(KitchenSink instance) => + { + 'no-42': instance.ctorValidatedNo42, + 'dateTime': instance.dateTime?.toIso8601String(), + 'bigInt': instance.bigInt?.toString(), + 'iterable': instance.iterable?.toList(), + 'dynamicIterable': instance.dynamicIterable?.toList(), + 'objectIterable': instance.objectIterable?.toList(), + 'intIterable': instance.intIterable?.toList(), + 'set': instance.set?.toList(), + 'dynamicSet': instance.dynamicSet?.toList(), + 'objectSet': instance.objectSet?.toList(), + 'intSet': instance.intSet?.toList(), + 'dateTimeSet': + instance.dateTimeSet?.map((e) => e?.toIso8601String())?.toList(), + 'datetime-iterable': + instance.dateTimeIterable?.map((e) => e?.toIso8601String())?.toList(), + 'list': instance.list, + 'dynamicList': instance.dynamicList, + 'objectList': instance.objectList, + 'intList': instance.intList, + 'dateTimeList': + instance.dateTimeList?.map((e) => e?.toIso8601String())?.toList(), + 'map': instance.map, + 'stringStringMap': instance.stringStringMap, + 'dynamicIntMap': instance.dynamicIntMap, + 'objectDateTimeMap': instance.objectDateTimeMap + ?.map((k, e) => MapEntry(k, e?.toIso8601String())), + 'crazyComplex': instance.crazyComplex + ?.map((e) => e?.map((k, e) => MapEntry( + k, + e?.map((k, e) => MapEntry( + k, + e + ?.map( + (e) => e?.map((e) => e?.toIso8601String())?.toList()) + ?.toList()))))) + ?.toList(), + 'val': instance.val, + 'writeNotNull': instance.writeNotNull, + r'$string': instance.string, + 'simpleObject': instance.simpleObject, + 'strictKeysObject': instance.strictKeysObject, + 'validatedPropertyNo42': instance.validatedPropertyNo42, + }; + +JsonConverterTestClass _$JsonConverterTestClassFromJson( + Map json) { + return JsonConverterTestClass() + ..duration = durationConverter.fromJson(json['duration'] as int) + ..durationList = (json['durationList'] as List) + ?.map((e) => durationConverter.fromJson(e as int)) + ?.toList() + ..bigInt = const BigIntStringConverter().fromJson(json['bigInt'] as String) + ..bigIntMap = (json['bigIntMap'] as Map)?.map( + (k, e) => + MapEntry(k, const BigIntStringConverter().fromJson(e as String)), + ) + ..numberSilly = + TrivialNumberConverter.instance.fromJson(json['numberSilly'] as int) + ..numberSillySet = (json['numberSillySet'] as List) + ?.map((e) => TrivialNumberConverter.instance.fromJson(e as int)) + ?.toSet() + ..dateTime = + const EpochDateTimeConverter().fromJson(json['dateTime'] as int); +} + +Map _$JsonConverterTestClassToJson( + JsonConverterTestClass instance) => + { + 'duration': durationConverter.toJson(instance.duration), + 'durationList': + instance.durationList?.map(durationConverter.toJson)?.toList(), + 'bigInt': const BigIntStringConverter().toJson(instance.bigInt), + 'bigIntMap': instance.bigIntMap + ?.map((k, e) => MapEntry(k, const BigIntStringConverter().toJson(e))), + 'numberSilly': + TrivialNumberConverter.instance.toJson(instance.numberSilly), + 'numberSillySet': instance.numberSillySet + ?.map(TrivialNumberConverter.instance.toJson) + ?.toList(), + 'dateTime': const EpochDateTimeConverter().toJson(instance.dateTime), + }; + +JsonConverterGeneric _$JsonConverterGenericFromJson( + Map json) { + return JsonConverterGeneric() + ..item = + GenericConverter().fromJson(json['item'] as Map) + ..itemList = (json['itemList'] as List) + ?.map((e) => GenericConverter().fromJson(e as Map)) + ?.toList() + ..itemMap = (json['itemMap'] as Map)?.map( + (k, e) => MapEntry( + k, GenericConverter().fromJson(e as Map)), + ); +} + +Map _$JsonConverterGenericToJson( + JsonConverterGeneric instance) => + { + 'item': GenericConverter().toJson(instance.item), + 'itemList': + instance.itemList?.map(GenericConverter().toJson)?.toList(), + 'itemMap': instance.itemMap + ?.map((k, e) => MapEntry(k, GenericConverter().toJson(e))), + }; diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map.dart new file mode 100644 index 000000000..b68578374 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map.dart @@ -0,0 +1,197 @@ +// 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. + +// ignore_for_file: annotate_overrides, hash_and_equals +import 'package:json_annotation/json_annotation.dart'; + +import 'json_converters.dart'; +import 'kitchen_sink_interface.dart' as k; +import 'simple_object.dart'; +import 'strict_keys_object.dart'; + +part 'kitchen_sink.g_any_map.g.dart'; + +// NOTE: these methods are replaced in the `non_nullable` cases to return +// non-null values. +List _defaultList() => null; +Set _defaultSet() => null; +Map _defaultMap() => null; +SimpleObject _defaultSimpleObject() => null; +StrictKeysObject _defaultStrictKeysObject() => null; + +const k.KitchenSinkFactory factory = _Factory(); + +class _Factory implements k.KitchenSinkFactory { + const _Factory(); + + String get description => 'any_map'; + bool get anyMap => true; + bool get checked => false; + bool get nullable => true; + bool get excludeNull => false; + bool get explicitToJson => false; + + k.KitchenSink ctor({ + int ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) => + KitchenSink( + ctorValidatedNo42: ctorValidatedNo42, + iterable: iterable, + dynamicIterable: dynamicIterable, + objectIterable: objectIterable, + intIterable: intIterable, + dateTimeIterable: dateTimeIterable, + ); + + k.KitchenSink fromJson(Map json) => KitchenSink.fromJson(json); + + k.JsonConverterTestClass jsonConverterCtor() => JsonConverterTestClass(); + + k.JsonConverterTestClass jsonConverterFromJson(Map json) => + JsonConverterTestClass.fromJson(json); +} + +@JsonSerializable( + anyMap: true, +) +class KitchenSink implements k.KitchenSink { + // NOTE: exposing these as Iterable, but storing the values as List + // to make the equality test work trivially. + final Iterable _iterable; + final Iterable _dynamicIterable; + final Iterable _objectIterable; + final Iterable _intIterable; + final Iterable _dateTimeIterable; + + @JsonKey(name: 'no-42') + final int ctorValidatedNo42; + + KitchenSink({ + this.ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) : _iterable = iterable?.toList() ?? _defaultList(), + _dynamicIterable = dynamicIterable?.toList() ?? _defaultList(), + _objectIterable = objectIterable?.toList() ?? _defaultList(), + _intIterable = intIterable?.toList() ?? _defaultList(), + _dateTimeIterable = dateTimeIterable?.toList() ?? _defaultList() { + if (ctorValidatedNo42 == 42) { + throw ArgumentError.value( + 42, 'ctorValidatedNo42', 'The value `42` is not allowed.'); + } + } + + factory KitchenSink.fromJson(Map json) => _$KitchenSinkFromJson(json); + + Map toJson() => _$KitchenSinkToJson(this); + + DateTime dateTime; + + BigInt bigInt; + + Iterable get iterable => _iterable; + Iterable get dynamicIterable => _dynamicIterable; + Iterable get objectIterable => _objectIterable; + Iterable get intIterable => _intIterable; + + Set set = _defaultSet(); + Set dynamicSet = _defaultSet(); + Set objectSet = _defaultSet(); + Set intSet = _defaultSet(); + Set dateTimeSet = _defaultSet(); + + // Added a one-off annotation on a property (not a field) + @JsonKey(name: 'datetime-iterable') + Iterable get dateTimeIterable => _dateTimeIterable; + + List list = _defaultList(); + List dynamicList = _defaultList(); + List objectList = _defaultList(); + List intList = _defaultList(); + List dateTimeList = _defaultList(); + + Map map = _defaultMap(); + Map stringStringMap = _defaultMap(); + Map dynamicIntMap = _defaultMap(); + Map objectDateTimeMap = _defaultMap(); + + List>>>> crazyComplex = + _defaultList(); + + // Handle fields with names that collide with helper names + Map val = _defaultMap(); + bool writeNotNull; + @JsonKey(name: r'$string') + String string; + + SimpleObject simpleObject = _defaultSimpleObject(); + + StrictKeysObject strictKeysObject = _defaultStrictKeysObject(); + + int _validatedPropertyNo42; + int get validatedPropertyNo42 => _validatedPropertyNo42; + + set validatedPropertyNo42(int value) { + if (value == 42) { + throw StateError('Cannot be 42!'); + } + _validatedPropertyNo42 = value; + } + + bool operator ==(Object other) => k.sinkEquals(this, other); +} + +@JsonSerializable( + anyMap: true, +) +// referencing a top-level field should work +@durationConverter +// referencing via a const constructor should work +@BigIntStringConverter() +@TrivialNumberConverter.instance +@EpochDateTimeConverter() +class JsonConverterTestClass implements k.JsonConverterTestClass { + JsonConverterTestClass(); + + factory JsonConverterTestClass.fromJson(Map json) => + _$JsonConverterTestClassFromJson(json); + + Map toJson() => _$JsonConverterTestClassToJson(this); + + Duration duration; + List durationList; + + BigInt bigInt; + Map bigIntMap; + + TrivialNumber numberSilly; + Set numberSillySet; + + DateTime dateTime; +} + +@JsonSerializable( + anyMap: true, +) +@GenericConverter() +class JsonConverterGeneric { + S item; + List itemList; + Map itemMap; + + JsonConverterGeneric(); + + factory JsonConverterGeneric.fromJson(Map json) => + _$JsonConverterGenericFromJson(json); + + Map toJson() => _$JsonConverterGenericToJson(this); +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map.g.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map.g.dart new file mode 100644 index 000000000..f57bdf7c6 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map.g.dart @@ -0,0 +1,184 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'kitchen_sink.g_any_map.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +KitchenSink _$KitchenSinkFromJson(Map json) { + return KitchenSink( + ctorValidatedNo42: json['no-42'] as int, + iterable: json['iterable'] as List, + dynamicIterable: json['dynamicIterable'] as List, + objectIterable: json['objectIterable'] as List, + intIterable: (json['intIterable'] as List)?.map((e) => e as int), + dateTimeIterable: (json['datetime-iterable'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)), + ) + ..dateTime = json['dateTime'] == null + ? null + : DateTime.parse(json['dateTime'] as String) + ..bigInt = + json['bigInt'] == null ? null : BigInt.parse(json['bigInt'] as String) + ..set = (json['set'] as List)?.toSet() + ..dynamicSet = (json['dynamicSet'] as List)?.toSet() + ..objectSet = (json['objectSet'] as List)?.toSet() + ..intSet = (json['intSet'] as List)?.map((e) => e as int)?.toSet() + ..dateTimeSet = (json['dateTimeSet'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)) + ?.toSet() + ..list = json['list'] as List + ..dynamicList = json['dynamicList'] as List + ..objectList = json['objectList'] as List + ..intList = (json['intList'] as List)?.map((e) => e as int)?.toList() + ..dateTimeList = (json['dateTimeList'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)) + ?.toList() + ..map = json['map'] as Map + ..stringStringMap = (json['stringStringMap'] as Map)?.map( + (k, e) => MapEntry(k as String, e as String), + ) + ..dynamicIntMap = (json['dynamicIntMap'] as Map)?.map( + (k, e) => MapEntry(k, e as int), + ) + ..objectDateTimeMap = (json['objectDateTimeMap'] as Map)?.map( + (k, e) => MapEntry(k, e == null ? null : DateTime.parse(e as String)), + ) + ..crazyComplex = (json['crazyComplex'] as List) + ?.map((e) => (e as Map)?.map( + (k, e) => MapEntry( + k as String, + (e as Map)?.map( + (k, e) => MapEntry( + k as String, + (e as List) + ?.map((e) => (e as List) + ?.map((e) => e == null + ? null + : DateTime.parse(e as String)) + ?.toList()) + ?.toList()), + )), + )) + ?.toList() + ..val = (json['val'] as Map)?.map( + (k, e) => MapEntry(k as String, e as bool), + ) + ..writeNotNull = json['writeNotNull'] as bool + ..string = json[r'$string'] as String + ..simpleObject = json['simpleObject'] == null + ? null + : SimpleObject.fromJson(json['simpleObject'] as Map) + ..strictKeysObject = json['strictKeysObject'] == null + ? null + : StrictKeysObject.fromJson(json['strictKeysObject'] as Map) + ..validatedPropertyNo42 = json['validatedPropertyNo42'] as int; +} + +Map _$KitchenSinkToJson(KitchenSink instance) => + { + 'no-42': instance.ctorValidatedNo42, + 'dateTime': instance.dateTime?.toIso8601String(), + 'bigInt': instance.bigInt?.toString(), + 'iterable': instance.iterable?.toList(), + 'dynamicIterable': instance.dynamicIterable?.toList(), + 'objectIterable': instance.objectIterable?.toList(), + 'intIterable': instance.intIterable?.toList(), + 'set': instance.set?.toList(), + 'dynamicSet': instance.dynamicSet?.toList(), + 'objectSet': instance.objectSet?.toList(), + 'intSet': instance.intSet?.toList(), + 'dateTimeSet': + instance.dateTimeSet?.map((e) => e?.toIso8601String())?.toList(), + 'datetime-iterable': + instance.dateTimeIterable?.map((e) => e?.toIso8601String())?.toList(), + 'list': instance.list, + 'dynamicList': instance.dynamicList, + 'objectList': instance.objectList, + 'intList': instance.intList, + 'dateTimeList': + instance.dateTimeList?.map((e) => e?.toIso8601String())?.toList(), + 'map': instance.map, + 'stringStringMap': instance.stringStringMap, + 'dynamicIntMap': instance.dynamicIntMap, + 'objectDateTimeMap': instance.objectDateTimeMap + ?.map((k, e) => MapEntry(k, e?.toIso8601String())), + 'crazyComplex': instance.crazyComplex + ?.map((e) => e?.map((k, e) => MapEntry( + k, + e?.map((k, e) => MapEntry( + k, + e + ?.map( + (e) => e?.map((e) => e?.toIso8601String())?.toList()) + ?.toList()))))) + ?.toList(), + 'val': instance.val, + 'writeNotNull': instance.writeNotNull, + r'$string': instance.string, + 'simpleObject': instance.simpleObject, + 'strictKeysObject': instance.strictKeysObject, + 'validatedPropertyNo42': instance.validatedPropertyNo42, + }; + +JsonConverterTestClass _$JsonConverterTestClassFromJson(Map json) { + return JsonConverterTestClass() + ..duration = durationConverter.fromJson(json['duration'] as int) + ..durationList = (json['durationList'] as List) + ?.map((e) => durationConverter.fromJson(e as int)) + ?.toList() + ..bigInt = const BigIntStringConverter().fromJson(json['bigInt'] as String) + ..bigIntMap = (json['bigIntMap'] as Map)?.map( + (k, e) => MapEntry( + k as String, const BigIntStringConverter().fromJson(e as String)), + ) + ..numberSilly = + TrivialNumberConverter.instance.fromJson(json['numberSilly'] as int) + ..numberSillySet = (json['numberSillySet'] as List) + ?.map((e) => TrivialNumberConverter.instance.fromJson(e as int)) + ?.toSet() + ..dateTime = + const EpochDateTimeConverter().fromJson(json['dateTime'] as int); +} + +Map _$JsonConverterTestClassToJson( + JsonConverterTestClass instance) => + { + 'duration': durationConverter.toJson(instance.duration), + 'durationList': + instance.durationList?.map(durationConverter.toJson)?.toList(), + 'bigInt': const BigIntStringConverter().toJson(instance.bigInt), + 'bigIntMap': instance.bigIntMap + ?.map((k, e) => MapEntry(k, const BigIntStringConverter().toJson(e))), + 'numberSilly': + TrivialNumberConverter.instance.toJson(instance.numberSilly), + 'numberSillySet': instance.numberSillySet + ?.map(TrivialNumberConverter.instance.toJson) + ?.toList(), + 'dateTime': const EpochDateTimeConverter().toJson(instance.dateTime), + }; + +JsonConverterGeneric _$JsonConverterGenericFromJson( + Map json) { + return JsonConverterGeneric() + ..item = + GenericConverter().fromJson(json['item'] as Map) + ..itemList = (json['itemList'] as List) + ?.map((e) => GenericConverter().fromJson(e as Map)) + ?.toList() + ..itemMap = (json['itemMap'] as Map)?.map( + (k, e) => MapEntry(k as String, + GenericConverter().fromJson(e as Map)), + ); +} + +Map _$JsonConverterGenericToJson( + JsonConverterGeneric instance) => + { + 'item': GenericConverter().toJson(instance.item), + 'itemList': + instance.itemList?.map(GenericConverter().toJson)?.toList(), + 'itemMap': instance.itemMap + ?.map((k, e) => MapEntry(k, GenericConverter().toJson(e))), + }; diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__checked__non_nullable.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__checked__non_nullable.dart new file mode 100644 index 000000000..dedc28fd4 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__checked__non_nullable.dart @@ -0,0 +1,203 @@ +// 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. + +// ignore_for_file: annotate_overrides, hash_and_equals +import 'package:json_annotation/json_annotation.dart'; + +import 'json_converters.dart'; +import 'kitchen_sink_interface.dart' as k; +import 'simple_object.dart'; +import 'strict_keys_object.dart'; + +part 'kitchen_sink.g_any_map__checked__non_nullable.g.dart'; + +// NOTE: these methods are replaced in the `non_nullable` cases to return +// non-null values. +List _defaultList() => []; +Set _defaultSet() => {}; +Map _defaultMap() => {}; +SimpleObject _defaultSimpleObject() => SimpleObject(42); +StrictKeysObject _defaultStrictKeysObject() => StrictKeysObject(10, 'cool'); + +const k.KitchenSinkFactory factory = _Factory(); + +class _Factory implements k.KitchenSinkFactory { + const _Factory(); + + String get description => 'any_map__checked__non_nullable'; + bool get anyMap => true; + bool get checked => true; + bool get nullable => false; + bool get excludeNull => false; + bool get explicitToJson => false; + + k.KitchenSink ctor({ + int ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) => + KitchenSink( + ctorValidatedNo42: ctorValidatedNo42, + iterable: iterable, + dynamicIterable: dynamicIterable, + objectIterable: objectIterable, + intIterable: intIterable, + dateTimeIterable: dateTimeIterable, + ); + + k.KitchenSink fromJson(Map json) => KitchenSink.fromJson(json); + + k.JsonConverterTestClass jsonConverterCtor() => JsonConverterTestClass(); + + k.JsonConverterTestClass jsonConverterFromJson(Map json) => + JsonConverterTestClass.fromJson(json); +} + +@JsonSerializable( + nullable: false, + checked: true, + anyMap: true, +) +class KitchenSink implements k.KitchenSink { + // NOTE: exposing these as Iterable, but storing the values as List + // to make the equality test work trivially. + final Iterable _iterable; + final Iterable _dynamicIterable; + final Iterable _objectIterable; + final Iterable _intIterable; + final Iterable _dateTimeIterable; + + @JsonKey(name: 'no-42') + final int ctorValidatedNo42; + + KitchenSink({ + this.ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) : _iterable = iterable?.toList() ?? _defaultList(), + _dynamicIterable = dynamicIterable?.toList() ?? _defaultList(), + _objectIterable = objectIterable?.toList() ?? _defaultList(), + _intIterable = intIterable?.toList() ?? _defaultList(), + _dateTimeIterable = dateTimeIterable?.toList() ?? _defaultList() { + if (ctorValidatedNo42 == 42) { + throw ArgumentError.value( + 42, 'ctorValidatedNo42', 'The value `42` is not allowed.'); + } + } + + factory KitchenSink.fromJson(Map json) => _$KitchenSinkFromJson(json); + + Map toJson() => _$KitchenSinkToJson(this); + + DateTime dateTime = DateTime(1981, 6, 5); + + BigInt bigInt = BigInt.parse('10000000000000000000'); + + Iterable get iterable => _iterable; + Iterable get dynamicIterable => _dynamicIterable; + Iterable get objectIterable => _objectIterable; + Iterable get intIterable => _intIterable; + + Set set = _defaultSet(); + Set dynamicSet = _defaultSet(); + Set objectSet = _defaultSet(); + Set intSet = _defaultSet(); + Set dateTimeSet = _defaultSet(); + + // Added a one-off annotation on a property (not a field) + @JsonKey(name: 'datetime-iterable') + Iterable get dateTimeIterable => _dateTimeIterable; + + List list = _defaultList(); + List dynamicList = _defaultList(); + List objectList = _defaultList(); + List intList = _defaultList(); + List dateTimeList = _defaultList(); + + Map map = _defaultMap(); + Map stringStringMap = _defaultMap(); + Map dynamicIntMap = _defaultMap(); + Map objectDateTimeMap = _defaultMap(); + + List>>>> crazyComplex = + _defaultList(); + + // Handle fields with names that collide with helper names + Map val = _defaultMap(); + bool writeNotNull; + @JsonKey(name: r'$string') + String string; + + SimpleObject simpleObject = _defaultSimpleObject(); + + StrictKeysObject strictKeysObject = _defaultStrictKeysObject(); + + int _validatedPropertyNo42; + int get validatedPropertyNo42 => _validatedPropertyNo42; + + set validatedPropertyNo42(int value) { + if (value == 42) { + throw StateError('Cannot be 42!'); + } + _validatedPropertyNo42 = value; + } + + bool operator ==(Object other) => k.sinkEquals(this, other); +} + +@JsonSerializable( + nullable: false, + checked: true, + anyMap: true, +) +// referencing a top-level field should work +@durationConverter +// referencing via a const constructor should work +@BigIntStringConverter() +@TrivialNumberConverter.instance +@EpochDateTimeConverter() +class JsonConverterTestClass implements k.JsonConverterTestClass { + JsonConverterTestClass(); + + factory JsonConverterTestClass.fromJson(Map json) => + _$JsonConverterTestClassFromJson(json); + + Map toJson() => _$JsonConverterTestClassToJson(this); + + Duration duration; + List durationList; + + BigInt bigInt = BigInt.parse('10000000000000000000'); + Map bigIntMap; + + TrivialNumber numberSilly; + Set numberSillySet; + + DateTime dateTime = DateTime(1981, 6, 5); +} + +@JsonSerializable( + nullable: false, + checked: true, + anyMap: true, +) +@GenericConverter() +class JsonConverterGeneric { + S item; + List itemList; + Map itemMap; + + JsonConverterGeneric(); + + factory JsonConverterGeneric.fromJson(Map json) => + _$JsonConverterGenericFromJson(json); + + Map toJson() => _$JsonConverterGenericToJson(this); +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__checked__non_nullable.g.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__checked__non_nullable.g.dart new file mode 100644 index 000000000..ec4f758f2 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__checked__non_nullable.g.dart @@ -0,0 +1,234 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'kitchen_sink.g_any_map__checked__non_nullable.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +KitchenSink _$KitchenSinkFromJson(Map json) { + return $checkedNew('KitchenSink', json, () { + final val = KitchenSink( + ctorValidatedNo42: $checkedConvert(json, 'no-42', (v) => v as int), + iterable: $checkedConvert(json, 'iterable', (v) => v as List), + dynamicIterable: + $checkedConvert(json, 'dynamicIterable', (v) => v as List), + objectIterable: $checkedConvert(json, 'objectIterable', (v) => v as List), + intIterable: $checkedConvert( + json, 'intIterable', (v) => (v as List).map((e) => e as int)), + dateTimeIterable: $checkedConvert(json, 'datetime-iterable', + (v) => (v as List).map((e) => DateTime.parse(e as String))), + ); + $checkedConvert( + json, 'dateTime', (v) => val.dateTime = DateTime.parse(v as String)); + $checkedConvert( + json, 'bigInt', (v) => val.bigInt = BigInt.parse(v as String)); + $checkedConvert(json, 'set', (v) => val.set = (v as List).toSet()); + $checkedConvert( + json, 'dynamicSet', (v) => val.dynamicSet = (v as List).toSet()); + $checkedConvert( + json, 'objectSet', (v) => val.objectSet = (v as List).toSet()); + $checkedConvert(json, 'intSet', + (v) => val.intSet = (v as List).map((e) => e as int).toSet()); + $checkedConvert( + json, + 'dateTimeSet', + (v) => val.dateTimeSet = + (v as List).map((e) => DateTime.parse(e as String)).toSet()); + $checkedConvert(json, 'list', (v) => val.list = v as List); + $checkedConvert(json, 'dynamicList', (v) => val.dynamicList = v as List); + $checkedConvert(json, 'objectList', (v) => val.objectList = v as List); + $checkedConvert(json, 'intList', + (v) => val.intList = (v as List).map((e) => e as int).toList()); + $checkedConvert( + json, + 'dateTimeList', + (v) => val.dateTimeList = + (v as List).map((e) => DateTime.parse(e as String)).toList()); + $checkedConvert(json, 'map', (v) => val.map = v as Map); + $checkedConvert(json, 'stringStringMap', + (v) => val.stringStringMap = Map.from(v as Map)); + $checkedConvert(json, 'dynamicIntMap', + (v) => val.dynamicIntMap = Map.from(v as Map)); + $checkedConvert( + json, + 'objectDateTimeMap', + (v) => val.objectDateTimeMap = (v as Map).map( + (k, e) => MapEntry(k, DateTime.parse(e as String)), + )); + $checkedConvert( + json, + 'crazyComplex', + (v) => val.crazyComplex = (v as List) + .map((e) => (e as Map).map( + (k, e) => MapEntry( + k as String, + (e as Map).map( + (k, e) => MapEntry( + k as String, + (e as List) + .map((e) => (e as List) + .map((e) => DateTime.parse(e as String)) + .toList()) + .toList()), + )), + )) + .toList()); + $checkedConvert( + json, 'val', (v) => val.val = Map.from(v as Map)); + $checkedConvert(json, 'writeNotNull', (v) => val.writeNotNull = v as bool); + $checkedConvert(json, r'$string', (v) => val.string = v as String); + $checkedConvert(json, 'simpleObject', + (v) => val.simpleObject = SimpleObject.fromJson(v as Map)); + $checkedConvert(json, 'strictKeysObject', + (v) => val.strictKeysObject = StrictKeysObject.fromJson(v as Map)); + $checkedConvert(json, 'validatedPropertyNo42', + (v) => val.validatedPropertyNo42 = v as int); + return val; + }, fieldKeyMap: const { + 'ctorValidatedNo42': 'no-42', + 'dateTimeIterable': 'datetime-iterable', + 'string': r'$string' + }); +} + +Map _$KitchenSinkToJson(KitchenSink instance) => + { + 'no-42': instance.ctorValidatedNo42, + 'dateTime': instance.dateTime.toIso8601String(), + 'bigInt': instance.bigInt.toString(), + 'iterable': instance.iterable.toList(), + 'dynamicIterable': instance.dynamicIterable.toList(), + 'objectIterable': instance.objectIterable.toList(), + 'intIterable': instance.intIterable.toList(), + 'set': instance.set.toList(), + 'dynamicSet': instance.dynamicSet.toList(), + 'objectSet': instance.objectSet.toList(), + 'intSet': instance.intSet.toList(), + 'dateTimeSet': + instance.dateTimeSet.map((e) => e.toIso8601String()).toList(), + 'datetime-iterable': + instance.dateTimeIterable.map((e) => e.toIso8601String()).toList(), + 'list': instance.list, + 'dynamicList': instance.dynamicList, + 'objectList': instance.objectList, + 'intList': instance.intList, + 'dateTimeList': + instance.dateTimeList.map((e) => e.toIso8601String()).toList(), + 'map': instance.map, + 'stringStringMap': instance.stringStringMap, + 'dynamicIntMap': instance.dynamicIntMap, + 'objectDateTimeMap': instance.objectDateTimeMap + .map((k, e) => MapEntry(k, e.toIso8601String())), + 'crazyComplex': instance.crazyComplex + .map((e) => e.map((k, e) => MapEntry( + k, + e.map((k, e) => MapEntry( + k, + e + .map((e) => e.map((e) => e.toIso8601String()).toList()) + .toList()))))) + .toList(), + 'val': instance.val, + 'writeNotNull': instance.writeNotNull, + r'$string': instance.string, + 'simpleObject': instance.simpleObject, + 'strictKeysObject': instance.strictKeysObject, + 'validatedPropertyNo42': instance.validatedPropertyNo42, + }; + +JsonConverterTestClass _$JsonConverterTestClassFromJson(Map json) { + return $checkedNew('JsonConverterTestClass', json, () { + final val = JsonConverterTestClass(); + $checkedConvert(json, 'duration', + (v) => val.duration = durationConverter.fromJson(v as int)); + $checkedConvert( + json, + 'durationList', + (v) => val.durationList = (v as List) + .map((e) => durationConverter.fromJson(e as int)) + .toList()); + $checkedConvert( + json, + 'bigInt', + (v) => + val.bigInt = const BigIntStringConverter().fromJson(v as String)); + $checkedConvert( + json, + 'bigIntMap', + (v) => val.bigIntMap = (v as Map).map( + (k, e) => MapEntry(k as String, + const BigIntStringConverter().fromJson(e as String)), + )); + $checkedConvert( + json, + 'numberSilly', + (v) => val.numberSilly = + TrivialNumberConverter.instance.fromJson(v as int)); + $checkedConvert( + json, + 'numberSillySet', + (v) => val.numberSillySet = (v as List) + .map((e) => TrivialNumberConverter.instance.fromJson(e as int)) + .toSet()); + $checkedConvert( + json, + 'dateTime', + (v) => + val.dateTime = const EpochDateTimeConverter().fromJson(v as int)); + return val; + }); +} + +Map _$JsonConverterTestClassToJson( + JsonConverterTestClass instance) => + { + 'duration': durationConverter.toJson(instance.duration), + 'durationList': + instance.durationList.map(durationConverter.toJson).toList(), + 'bigInt': const BigIntStringConverter().toJson(instance.bigInt), + 'bigIntMap': instance.bigIntMap + .map((k, e) => MapEntry(k, const BigIntStringConverter().toJson(e))), + 'numberSilly': + TrivialNumberConverter.instance.toJson(instance.numberSilly), + 'numberSillySet': instance.numberSillySet + .map(TrivialNumberConverter.instance.toJson) + .toList(), + 'dateTime': const EpochDateTimeConverter().toJson(instance.dateTime), + }; + +JsonConverterGeneric _$JsonConverterGenericFromJson( + Map json) { + return $checkedNew('JsonConverterGeneric', json, () { + final val = JsonConverterGeneric(); + $checkedConvert( + json, + 'item', + (v) => val.item = + GenericConverter().fromJson(v as Map)); + $checkedConvert( + json, + 'itemList', + (v) => val.itemList = (v as List) + .map((e) => + GenericConverter().fromJson(e as Map)) + .toList()); + $checkedConvert( + json, + 'itemMap', + (v) => val.itemMap = (v as Map).map( + (k, e) => MapEntry(k as String, + GenericConverter().fromJson(e as Map)), + )); + return val; + }); +} + +Map _$JsonConverterGenericToJson( + JsonConverterGeneric instance) => + { + 'item': GenericConverter().toJson(instance.item), + 'itemList': instance.itemList.map(GenericConverter().toJson).toList(), + 'itemMap': instance.itemMap + .map((k, e) => MapEntry(k, GenericConverter().toJson(e))), + }; diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__non_nullable.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__non_nullable.dart new file mode 100644 index 000000000..7185c5243 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__non_nullable.dart @@ -0,0 +1,200 @@ +// 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. + +// ignore_for_file: annotate_overrides, hash_and_equals +import 'package:json_annotation/json_annotation.dart'; + +import 'json_converters.dart'; +import 'kitchen_sink_interface.dart' as k; +import 'simple_object.dart'; +import 'strict_keys_object.dart'; + +part 'kitchen_sink.g_any_map__non_nullable.g.dart'; + +// NOTE: these methods are replaced in the `non_nullable` cases to return +// non-null values. +List _defaultList() => []; +Set _defaultSet() => {}; +Map _defaultMap() => {}; +SimpleObject _defaultSimpleObject() => SimpleObject(42); +StrictKeysObject _defaultStrictKeysObject() => StrictKeysObject(10, 'cool'); + +const k.KitchenSinkFactory factory = _Factory(); + +class _Factory implements k.KitchenSinkFactory { + const _Factory(); + + String get description => 'any_map__non_nullable'; + bool get anyMap => true; + bool get checked => false; + bool get nullable => false; + bool get excludeNull => false; + bool get explicitToJson => false; + + k.KitchenSink ctor({ + int ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) => + KitchenSink( + ctorValidatedNo42: ctorValidatedNo42, + iterable: iterable, + dynamicIterable: dynamicIterable, + objectIterable: objectIterable, + intIterable: intIterable, + dateTimeIterable: dateTimeIterable, + ); + + k.KitchenSink fromJson(Map json) => KitchenSink.fromJson(json); + + k.JsonConverterTestClass jsonConverterCtor() => JsonConverterTestClass(); + + k.JsonConverterTestClass jsonConverterFromJson(Map json) => + JsonConverterTestClass.fromJson(json); +} + +@JsonSerializable( + nullable: false, + anyMap: true, +) +class KitchenSink implements k.KitchenSink { + // NOTE: exposing these as Iterable, but storing the values as List + // to make the equality test work trivially. + final Iterable _iterable; + final Iterable _dynamicIterable; + final Iterable _objectIterable; + final Iterable _intIterable; + final Iterable _dateTimeIterable; + + @JsonKey(name: 'no-42') + final int ctorValidatedNo42; + + KitchenSink({ + this.ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) : _iterable = iterable?.toList() ?? _defaultList(), + _dynamicIterable = dynamicIterable?.toList() ?? _defaultList(), + _objectIterable = objectIterable?.toList() ?? _defaultList(), + _intIterable = intIterable?.toList() ?? _defaultList(), + _dateTimeIterable = dateTimeIterable?.toList() ?? _defaultList() { + if (ctorValidatedNo42 == 42) { + throw ArgumentError.value( + 42, 'ctorValidatedNo42', 'The value `42` is not allowed.'); + } + } + + factory KitchenSink.fromJson(Map json) => _$KitchenSinkFromJson(json); + + Map toJson() => _$KitchenSinkToJson(this); + + DateTime dateTime = DateTime(1981, 6, 5); + + BigInt bigInt = BigInt.parse('10000000000000000000'); + + Iterable get iterable => _iterable; + Iterable get dynamicIterable => _dynamicIterable; + Iterable get objectIterable => _objectIterable; + Iterable get intIterable => _intIterable; + + Set set = _defaultSet(); + Set dynamicSet = _defaultSet(); + Set objectSet = _defaultSet(); + Set intSet = _defaultSet(); + Set dateTimeSet = _defaultSet(); + + // Added a one-off annotation on a property (not a field) + @JsonKey(name: 'datetime-iterable') + Iterable get dateTimeIterable => _dateTimeIterable; + + List list = _defaultList(); + List dynamicList = _defaultList(); + List objectList = _defaultList(); + List intList = _defaultList(); + List dateTimeList = _defaultList(); + + Map map = _defaultMap(); + Map stringStringMap = _defaultMap(); + Map dynamicIntMap = _defaultMap(); + Map objectDateTimeMap = _defaultMap(); + + List>>>> crazyComplex = + _defaultList(); + + // Handle fields with names that collide with helper names + Map val = _defaultMap(); + bool writeNotNull; + @JsonKey(name: r'$string') + String string; + + SimpleObject simpleObject = _defaultSimpleObject(); + + StrictKeysObject strictKeysObject = _defaultStrictKeysObject(); + + int _validatedPropertyNo42; + int get validatedPropertyNo42 => _validatedPropertyNo42; + + set validatedPropertyNo42(int value) { + if (value == 42) { + throw StateError('Cannot be 42!'); + } + _validatedPropertyNo42 = value; + } + + bool operator ==(Object other) => k.sinkEquals(this, other); +} + +@JsonSerializable( + nullable: false, + anyMap: true, +) +// referencing a top-level field should work +@durationConverter +// referencing via a const constructor should work +@BigIntStringConverter() +@TrivialNumberConverter.instance +@EpochDateTimeConverter() +class JsonConverterTestClass implements k.JsonConverterTestClass { + JsonConverterTestClass(); + + factory JsonConverterTestClass.fromJson(Map json) => + _$JsonConverterTestClassFromJson(json); + + Map toJson() => _$JsonConverterTestClassToJson(this); + + Duration duration; + List durationList; + + BigInt bigInt = BigInt.parse('10000000000000000000'); + Map bigIntMap; + + TrivialNumber numberSilly; + Set numberSillySet; + + DateTime dateTime = DateTime(1981, 6, 5); +} + +@JsonSerializable( + nullable: false, + anyMap: true, +) +@GenericConverter() +class JsonConverterGeneric { + S item; + List itemList; + Map itemMap; + + JsonConverterGeneric(); + + factory JsonConverterGeneric.fromJson(Map json) => + _$JsonConverterGenericFromJson(json); + + Map toJson() => _$JsonConverterGenericToJson(this); +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__non_nullable.g.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__non_nullable.g.dart new file mode 100644 index 000000000..e06c0f1be --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_any_map__non_nullable.g.dart @@ -0,0 +1,168 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'kitchen_sink.g_any_map__non_nullable.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +KitchenSink _$KitchenSinkFromJson(Map json) { + return KitchenSink( + ctorValidatedNo42: json['no-42'] as int, + iterable: json['iterable'] as List, + dynamicIterable: json['dynamicIterable'] as List, + objectIterable: json['objectIterable'] as List, + intIterable: (json['intIterable'] as List).map((e) => e as int), + dateTimeIterable: (json['datetime-iterable'] as List) + .map((e) => DateTime.parse(e as String)), + ) + ..dateTime = DateTime.parse(json['dateTime'] as String) + ..bigInt = BigInt.parse(json['bigInt'] as String) + ..set = (json['set'] as List).toSet() + ..dynamicSet = (json['dynamicSet'] as List).toSet() + ..objectSet = (json['objectSet'] as List).toSet() + ..intSet = (json['intSet'] as List).map((e) => e as int).toSet() + ..dateTimeSet = (json['dateTimeSet'] as List) + .map((e) => DateTime.parse(e as String)) + .toSet() + ..list = json['list'] as List + ..dynamicList = json['dynamicList'] as List + ..objectList = json['objectList'] as List + ..intList = (json['intList'] as List).map((e) => e as int).toList() + ..dateTimeList = (json['dateTimeList'] as List) + .map((e) => DateTime.parse(e as String)) + .toList() + ..map = json['map'] as Map + ..stringStringMap = Map.from(json['stringStringMap'] as Map) + ..dynamicIntMap = Map.from(json['dynamicIntMap'] as Map) + ..objectDateTimeMap = (json['objectDateTimeMap'] as Map).map( + (k, e) => MapEntry(k, DateTime.parse(e as String)), + ) + ..crazyComplex = (json['crazyComplex'] as List) + .map((e) => (e as Map).map( + (k, e) => MapEntry( + k as String, + (e as Map).map( + (k, e) => MapEntry( + k as String, + (e as List) + .map((e) => (e as List) + .map((e) => DateTime.parse(e as String)) + .toList()) + .toList()), + )), + )) + .toList() + ..val = Map.from(json['val'] as Map) + ..writeNotNull = json['writeNotNull'] as bool + ..string = json[r'$string'] as String + ..simpleObject = SimpleObject.fromJson(json['simpleObject'] as Map) + ..strictKeysObject = + StrictKeysObject.fromJson(json['strictKeysObject'] as Map) + ..validatedPropertyNo42 = json['validatedPropertyNo42'] as int; +} + +Map _$KitchenSinkToJson(KitchenSink instance) => + { + 'no-42': instance.ctorValidatedNo42, + 'dateTime': instance.dateTime.toIso8601String(), + 'bigInt': instance.bigInt.toString(), + 'iterable': instance.iterable.toList(), + 'dynamicIterable': instance.dynamicIterable.toList(), + 'objectIterable': instance.objectIterable.toList(), + 'intIterable': instance.intIterable.toList(), + 'set': instance.set.toList(), + 'dynamicSet': instance.dynamicSet.toList(), + 'objectSet': instance.objectSet.toList(), + 'intSet': instance.intSet.toList(), + 'dateTimeSet': + instance.dateTimeSet.map((e) => e.toIso8601String()).toList(), + 'datetime-iterable': + instance.dateTimeIterable.map((e) => e.toIso8601String()).toList(), + 'list': instance.list, + 'dynamicList': instance.dynamicList, + 'objectList': instance.objectList, + 'intList': instance.intList, + 'dateTimeList': + instance.dateTimeList.map((e) => e.toIso8601String()).toList(), + 'map': instance.map, + 'stringStringMap': instance.stringStringMap, + 'dynamicIntMap': instance.dynamicIntMap, + 'objectDateTimeMap': instance.objectDateTimeMap + .map((k, e) => MapEntry(k, e.toIso8601String())), + 'crazyComplex': instance.crazyComplex + .map((e) => e.map((k, e) => MapEntry( + k, + e.map((k, e) => MapEntry( + k, + e + .map((e) => e.map((e) => e.toIso8601String()).toList()) + .toList()))))) + .toList(), + 'val': instance.val, + 'writeNotNull': instance.writeNotNull, + r'$string': instance.string, + 'simpleObject': instance.simpleObject, + 'strictKeysObject': instance.strictKeysObject, + 'validatedPropertyNo42': instance.validatedPropertyNo42, + }; + +JsonConverterTestClass _$JsonConverterTestClassFromJson(Map json) { + return JsonConverterTestClass() + ..duration = durationConverter.fromJson(json['duration'] as int) + ..durationList = (json['durationList'] as List) + .map((e) => durationConverter.fromJson(e as int)) + .toList() + ..bigInt = const BigIntStringConverter().fromJson(json['bigInt'] as String) + ..bigIntMap = (json['bigIntMap'] as Map).map( + (k, e) => MapEntry( + k as String, const BigIntStringConverter().fromJson(e as String)), + ) + ..numberSilly = + TrivialNumberConverter.instance.fromJson(json['numberSilly'] as int) + ..numberSillySet = (json['numberSillySet'] as List) + .map((e) => TrivialNumberConverter.instance.fromJson(e as int)) + .toSet() + ..dateTime = + const EpochDateTimeConverter().fromJson(json['dateTime'] as int); +} + +Map _$JsonConverterTestClassToJson( + JsonConverterTestClass instance) => + { + 'duration': durationConverter.toJson(instance.duration), + 'durationList': + instance.durationList.map(durationConverter.toJson).toList(), + 'bigInt': const BigIntStringConverter().toJson(instance.bigInt), + 'bigIntMap': instance.bigIntMap + .map((k, e) => MapEntry(k, const BigIntStringConverter().toJson(e))), + 'numberSilly': + TrivialNumberConverter.instance.toJson(instance.numberSilly), + 'numberSillySet': instance.numberSillySet + .map(TrivialNumberConverter.instance.toJson) + .toList(), + 'dateTime': const EpochDateTimeConverter().toJson(instance.dateTime), + }; + +JsonConverterGeneric _$JsonConverterGenericFromJson( + Map json) { + return JsonConverterGeneric() + ..item = + GenericConverter().fromJson(json['item'] as Map) + ..itemList = (json['itemList'] as List) + .map((e) => GenericConverter().fromJson(e as Map)) + .toList() + ..itemMap = (json['itemMap'] as Map).map( + (k, e) => MapEntry(k as String, + GenericConverter().fromJson(e as Map)), + ); +} + +Map _$JsonConverterGenericToJson( + JsonConverterGeneric instance) => + { + 'item': GenericConverter().toJson(instance.item), + 'itemList': instance.itemList.map(GenericConverter().toJson).toList(), + 'itemMap': instance.itemMap + .map((k, e) => MapEntry(k, GenericConverter().toJson(e))), + }; diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null.dart new file mode 100644 index 000000000..27cedf69b --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null.dart @@ -0,0 +1,199 @@ +// 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. + +// ignore_for_file: annotate_overrides, hash_and_equals +import 'package:json_annotation/json_annotation.dart'; + +import 'json_converters.dart'; +import 'kitchen_sink_interface.dart' as k; +import 'simple_object.dart'; +import 'strict_keys_object.dart'; + +part 'kitchen_sink.g_exclude_null.g.dart'; + +// NOTE: these methods are replaced in the `non_nullable` cases to return +// non-null values. +List _defaultList() => null; +Set _defaultSet() => null; +Map _defaultMap() => null; +SimpleObject _defaultSimpleObject() => null; +StrictKeysObject _defaultStrictKeysObject() => null; + +const k.KitchenSinkFactory factory = _Factory(); + +class _Factory implements k.KitchenSinkFactory { + const _Factory(); + + String get description => 'exclude_null'; + bool get anyMap => false; + bool get checked => false; + bool get nullable => true; + bool get excludeNull => true; + bool get explicitToJson => false; + + k.KitchenSink ctor({ + int ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) => + KitchenSink( + ctorValidatedNo42: ctorValidatedNo42, + iterable: iterable, + dynamicIterable: dynamicIterable, + objectIterable: objectIterable, + intIterable: intIterable, + dateTimeIterable: dateTimeIterable, + ); + + k.KitchenSink fromJson(Map json) => + KitchenSink.fromJson(json); + + k.JsonConverterTestClass jsonConverterCtor() => JsonConverterTestClass(); + + k.JsonConverterTestClass jsonConverterFromJson(Map json) => + JsonConverterTestClass.fromJson(json); +} + +@JsonSerializable( + includeIfNull: false, +) +class KitchenSink implements k.KitchenSink { + // NOTE: exposing these as Iterable, but storing the values as List + // to make the equality test work trivially. + final Iterable _iterable; + final Iterable _dynamicIterable; + final Iterable _objectIterable; + final Iterable _intIterable; + final Iterable _dateTimeIterable; + + @JsonKey(name: 'no-42') + final int ctorValidatedNo42; + + KitchenSink({ + this.ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) : _iterable = iterable?.toList() ?? _defaultList(), + _dynamicIterable = dynamicIterable?.toList() ?? _defaultList(), + _objectIterable = objectIterable?.toList() ?? _defaultList(), + _intIterable = intIterable?.toList() ?? _defaultList(), + _dateTimeIterable = dateTimeIterable?.toList() ?? _defaultList() { + if (ctorValidatedNo42 == 42) { + throw ArgumentError.value( + 42, 'ctorValidatedNo42', 'The value `42` is not allowed.'); + } + } + + factory KitchenSink.fromJson(Map json) => + _$KitchenSinkFromJson(json); + + Map toJson() => _$KitchenSinkToJson(this); + + DateTime dateTime; + + BigInt bigInt; + + Iterable get iterable => _iterable; + Iterable get dynamicIterable => _dynamicIterable; + Iterable get objectIterable => _objectIterable; + Iterable get intIterable => _intIterable; + + Set set = _defaultSet(); + Set dynamicSet = _defaultSet(); + Set objectSet = _defaultSet(); + Set intSet = _defaultSet(); + Set dateTimeSet = _defaultSet(); + + // Added a one-off annotation on a property (not a field) + @JsonKey(name: 'datetime-iterable') + Iterable get dateTimeIterable => _dateTimeIterable; + + List list = _defaultList(); + List dynamicList = _defaultList(); + List objectList = _defaultList(); + List intList = _defaultList(); + List dateTimeList = _defaultList(); + + Map map = _defaultMap(); + Map stringStringMap = _defaultMap(); + Map dynamicIntMap = _defaultMap(); + Map objectDateTimeMap = _defaultMap(); + + List>>>> crazyComplex = + _defaultList(); + + // Handle fields with names that collide with helper names + Map val = _defaultMap(); + bool writeNotNull; + @JsonKey(name: r'$string') + String string; + + SimpleObject simpleObject = _defaultSimpleObject(); + + StrictKeysObject strictKeysObject = _defaultStrictKeysObject(); + + int _validatedPropertyNo42; + int get validatedPropertyNo42 => _validatedPropertyNo42; + + set validatedPropertyNo42(int value) { + if (value == 42) { + throw StateError('Cannot be 42!'); + } + _validatedPropertyNo42 = value; + } + + bool operator ==(Object other) => k.sinkEquals(this, other); +} + +@JsonSerializable( + includeIfNull: false, +) +// referencing a top-level field should work +@durationConverter +// referencing via a const constructor should work +@BigIntStringConverter() +@TrivialNumberConverter.instance +@EpochDateTimeConverter() +class JsonConverterTestClass implements k.JsonConverterTestClass { + JsonConverterTestClass(); + + factory JsonConverterTestClass.fromJson(Map json) => + _$JsonConverterTestClassFromJson(json); + + Map toJson() => _$JsonConverterTestClassToJson(this); + + Duration duration; + List durationList; + + BigInt bigInt; + Map bigIntMap; + + TrivialNumber numberSilly; + Set numberSillySet; + + DateTime dateTime; +} + +@JsonSerializable( + includeIfNull: false, +) +@GenericConverter() +class JsonConverterGeneric { + S item; + List itemList; + Map itemMap; + + JsonConverterGeneric(); + + factory JsonConverterGeneric.fromJson(Map json) => + _$JsonConverterGenericFromJson(json); + + Map toJson() => _$JsonConverterGenericToJson(this); +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null.g.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null.g.dart new file mode 100644 index 000000000..52c5be511 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null.g.dart @@ -0,0 +1,222 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'kitchen_sink.g_exclude_null.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +KitchenSink _$KitchenSinkFromJson(Map json) { + return KitchenSink( + ctorValidatedNo42: json['no-42'] as int, + iterable: json['iterable'] as List, + dynamicIterable: json['dynamicIterable'] as List, + objectIterable: json['objectIterable'] as List, + intIterable: (json['intIterable'] as List)?.map((e) => e as int), + dateTimeIterable: (json['datetime-iterable'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)), + ) + ..dateTime = json['dateTime'] == null + ? null + : DateTime.parse(json['dateTime'] as String) + ..bigInt = + json['bigInt'] == null ? null : BigInt.parse(json['bigInt'] as String) + ..set = (json['set'] as List)?.toSet() + ..dynamicSet = (json['dynamicSet'] as List)?.toSet() + ..objectSet = (json['objectSet'] as List)?.toSet() + ..intSet = (json['intSet'] as List)?.map((e) => e as int)?.toSet() + ..dateTimeSet = (json['dateTimeSet'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)) + ?.toSet() + ..list = json['list'] as List + ..dynamicList = json['dynamicList'] as List + ..objectList = json['objectList'] as List + ..intList = (json['intList'] as List)?.map((e) => e as int)?.toList() + ..dateTimeList = (json['dateTimeList'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)) + ?.toList() + ..map = json['map'] as Map + ..stringStringMap = (json['stringStringMap'] as Map)?.map( + (k, e) => MapEntry(k, e as String), + ) + ..dynamicIntMap = (json['dynamicIntMap'] as Map)?.map( + (k, e) => MapEntry(k, e as int), + ) + ..objectDateTimeMap = + (json['objectDateTimeMap'] as Map)?.map( + (k, e) => MapEntry(k, e == null ? null : DateTime.parse(e as String)), + ) + ..crazyComplex = (json['crazyComplex'] as List) + ?.map((e) => (e as Map)?.map( + (k, e) => MapEntry( + k, + (e as Map)?.map( + (k, e) => MapEntry( + k, + (e as List) + ?.map((e) => (e as List) + ?.map((e) => e == null + ? null + : DateTime.parse(e as String)) + ?.toList()) + ?.toList()), + )), + )) + ?.toList() + ..val = (json['val'] as Map)?.map( + (k, e) => MapEntry(k, e as bool), + ) + ..writeNotNull = json['writeNotNull'] as bool + ..string = json[r'$string'] as String + ..simpleObject = json['simpleObject'] == null + ? null + : SimpleObject.fromJson(json['simpleObject'] as Map) + ..strictKeysObject = json['strictKeysObject'] == null + ? null + : StrictKeysObject.fromJson( + json['strictKeysObject'] as Map) + ..validatedPropertyNo42 = json['validatedPropertyNo42'] as int; +} + +Map _$KitchenSinkToJson(KitchenSink instance) { + final val = {}; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('no-42', instance.ctorValidatedNo42); + writeNotNull('dateTime', instance.dateTime?.toIso8601String()); + writeNotNull('bigInt', instance.bigInt?.toString()); + writeNotNull('iterable', instance.iterable?.toList()); + writeNotNull('dynamicIterable', instance.dynamicIterable?.toList()); + writeNotNull('objectIterable', instance.objectIterable?.toList()); + writeNotNull('intIterable', instance.intIterable?.toList()); + writeNotNull('set', instance.set?.toList()); + writeNotNull('dynamicSet', instance.dynamicSet?.toList()); + writeNotNull('objectSet', instance.objectSet?.toList()); + writeNotNull('intSet', instance.intSet?.toList()); + writeNotNull('dateTimeSet', + instance.dateTimeSet?.map((e) => e?.toIso8601String())?.toList()); + writeNotNull('datetime-iterable', + instance.dateTimeIterable?.map((e) => e?.toIso8601String())?.toList()); + writeNotNull('list', instance.list); + writeNotNull('dynamicList', instance.dynamicList); + writeNotNull('objectList', instance.objectList); + writeNotNull('intList', instance.intList); + writeNotNull('dateTimeList', + instance.dateTimeList?.map((e) => e?.toIso8601String())?.toList()); + writeNotNull('map', instance.map); + writeNotNull('stringStringMap', instance.stringStringMap); + writeNotNull('dynamicIntMap', instance.dynamicIntMap); + writeNotNull( + 'objectDateTimeMap', + instance.objectDateTimeMap + ?.map((k, e) => MapEntry(k, e?.toIso8601String()))); + writeNotNull( + 'crazyComplex', + instance.crazyComplex + ?.map((e) => e?.map((k, e) => MapEntry( + k, + e?.map((k, e) => MapEntry( + k, + e + ?.map( + (e) => e?.map((e) => e?.toIso8601String())?.toList()) + ?.toList()))))) + ?.toList()); + writeNotNull('val', instance.val); + writeNotNull('writeNotNull', instance.writeNotNull); + writeNotNull(r'$string', instance.string); + writeNotNull('simpleObject', instance.simpleObject); + writeNotNull('strictKeysObject', instance.strictKeysObject); + writeNotNull('validatedPropertyNo42', instance.validatedPropertyNo42); + return val; +} + +JsonConverterTestClass _$JsonConverterTestClassFromJson( + Map json) { + return JsonConverterTestClass() + ..duration = durationConverter.fromJson(json['duration'] as int) + ..durationList = (json['durationList'] as List) + ?.map((e) => durationConverter.fromJson(e as int)) + ?.toList() + ..bigInt = const BigIntStringConverter().fromJson(json['bigInt'] as String) + ..bigIntMap = (json['bigIntMap'] as Map)?.map( + (k, e) => + MapEntry(k, const BigIntStringConverter().fromJson(e as String)), + ) + ..numberSilly = + TrivialNumberConverter.instance.fromJson(json['numberSilly'] as int) + ..numberSillySet = (json['numberSillySet'] as List) + ?.map((e) => TrivialNumberConverter.instance.fromJson(e as int)) + ?.toSet() + ..dateTime = + const EpochDateTimeConverter().fromJson(json['dateTime'] as int); +} + +Map _$JsonConverterTestClassToJson( + JsonConverterTestClass instance) { + final val = {}; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('duration', durationConverter.toJson(instance.duration)); + writeNotNull('durationList', + instance.durationList?.map(durationConverter.toJson)?.toList()); + writeNotNull('bigInt', const BigIntStringConverter().toJson(instance.bigInt)); + writeNotNull( + 'bigIntMap', + instance.bigIntMap?.map( + (k, e) => MapEntry(k, const BigIntStringConverter().toJson(e)))); + writeNotNull('numberSilly', + TrivialNumberConverter.instance.toJson(instance.numberSilly)); + writeNotNull( + 'numberSillySet', + instance.numberSillySet + ?.map(TrivialNumberConverter.instance.toJson) + ?.toList()); + writeNotNull( + 'dateTime', const EpochDateTimeConverter().toJson(instance.dateTime)); + return val; +} + +JsonConverterGeneric _$JsonConverterGenericFromJson( + Map json) { + return JsonConverterGeneric() + ..item = + GenericConverter().fromJson(json['item'] as Map) + ..itemList = (json['itemList'] as List) + ?.map((e) => GenericConverter().fromJson(e as Map)) + ?.toList() + ..itemMap = (json['itemMap'] as Map)?.map( + (k, e) => MapEntry( + k, GenericConverter().fromJson(e as Map)), + ); +} + +Map _$JsonConverterGenericToJson( + JsonConverterGeneric instance) { + final val = {}; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('item', GenericConverter().toJson(instance.item)); + writeNotNull('itemList', + instance.itemList?.map(GenericConverter().toJson)?.toList()); + writeNotNull( + 'itemMap', + instance.itemMap + ?.map((k, e) => MapEntry(k, GenericConverter().toJson(e)))); + return val; +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null__non_nullable.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null__non_nullable.dart new file mode 100644 index 000000000..194d406a8 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null__non_nullable.dart @@ -0,0 +1,202 @@ +// 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. + +// ignore_for_file: annotate_overrides, hash_and_equals +import 'package:json_annotation/json_annotation.dart'; + +import 'json_converters.dart'; +import 'kitchen_sink_interface.dart' as k; +import 'simple_object.dart'; +import 'strict_keys_object.dart'; + +part 'kitchen_sink.g_exclude_null__non_nullable.g.dart'; + +// NOTE: these methods are replaced in the `non_nullable` cases to return +// non-null values. +List _defaultList() => []; +Set _defaultSet() => {}; +Map _defaultMap() => {}; +SimpleObject _defaultSimpleObject() => SimpleObject(42); +StrictKeysObject _defaultStrictKeysObject() => StrictKeysObject(10, 'cool'); + +const k.KitchenSinkFactory factory = _Factory(); + +class _Factory implements k.KitchenSinkFactory { + const _Factory(); + + String get description => 'exclude_null__non_nullable'; + bool get anyMap => false; + bool get checked => false; + bool get nullable => false; + bool get excludeNull => true; + bool get explicitToJson => false; + + k.KitchenSink ctor({ + int ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) => + KitchenSink( + ctorValidatedNo42: ctorValidatedNo42, + iterable: iterable, + dynamicIterable: dynamicIterable, + objectIterable: objectIterable, + intIterable: intIterable, + dateTimeIterable: dateTimeIterable, + ); + + k.KitchenSink fromJson(Map json) => + KitchenSink.fromJson(json); + + k.JsonConverterTestClass jsonConverterCtor() => JsonConverterTestClass(); + + k.JsonConverterTestClass jsonConverterFromJson(Map json) => + JsonConverterTestClass.fromJson(json); +} + +@JsonSerializable( + nullable: false, + includeIfNull: false, +) +class KitchenSink implements k.KitchenSink { + // NOTE: exposing these as Iterable, but storing the values as List + // to make the equality test work trivially. + final Iterable _iterable; + final Iterable _dynamicIterable; + final Iterable _objectIterable; + final Iterable _intIterable; + final Iterable _dateTimeIterable; + + @JsonKey(name: 'no-42') + final int ctorValidatedNo42; + + KitchenSink({ + this.ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) : _iterable = iterable?.toList() ?? _defaultList(), + _dynamicIterable = dynamicIterable?.toList() ?? _defaultList(), + _objectIterable = objectIterable?.toList() ?? _defaultList(), + _intIterable = intIterable?.toList() ?? _defaultList(), + _dateTimeIterable = dateTimeIterable?.toList() ?? _defaultList() { + if (ctorValidatedNo42 == 42) { + throw ArgumentError.value( + 42, 'ctorValidatedNo42', 'The value `42` is not allowed.'); + } + } + + factory KitchenSink.fromJson(Map json) => + _$KitchenSinkFromJson(json); + + Map toJson() => _$KitchenSinkToJson(this); + + DateTime dateTime = DateTime(1981, 6, 5); + + BigInt bigInt = BigInt.parse('10000000000000000000'); + + Iterable get iterable => _iterable; + Iterable get dynamicIterable => _dynamicIterable; + Iterable get objectIterable => _objectIterable; + Iterable get intIterable => _intIterable; + + Set set = _defaultSet(); + Set dynamicSet = _defaultSet(); + Set objectSet = _defaultSet(); + Set intSet = _defaultSet(); + Set dateTimeSet = _defaultSet(); + + // Added a one-off annotation on a property (not a field) + @JsonKey(name: 'datetime-iterable') + Iterable get dateTimeIterable => _dateTimeIterable; + + List list = _defaultList(); + List dynamicList = _defaultList(); + List objectList = _defaultList(); + List intList = _defaultList(); + List dateTimeList = _defaultList(); + + Map map = _defaultMap(); + Map stringStringMap = _defaultMap(); + Map dynamicIntMap = _defaultMap(); + Map objectDateTimeMap = _defaultMap(); + + List>>>> crazyComplex = + _defaultList(); + + // Handle fields with names that collide with helper names + Map val = _defaultMap(); + bool writeNotNull; + @JsonKey(name: r'$string') + String string; + + SimpleObject simpleObject = _defaultSimpleObject(); + + StrictKeysObject strictKeysObject = _defaultStrictKeysObject(); + + int _validatedPropertyNo42; + int get validatedPropertyNo42 => _validatedPropertyNo42; + + set validatedPropertyNo42(int value) { + if (value == 42) { + throw StateError('Cannot be 42!'); + } + _validatedPropertyNo42 = value; + } + + bool operator ==(Object other) => k.sinkEquals(this, other); +} + +@JsonSerializable( + nullable: false, + includeIfNull: false, +) +// referencing a top-level field should work +@durationConverter +// referencing via a const constructor should work +@BigIntStringConverter() +@TrivialNumberConverter.instance +@EpochDateTimeConverter() +class JsonConverterTestClass implements k.JsonConverterTestClass { + JsonConverterTestClass(); + + factory JsonConverterTestClass.fromJson(Map json) => + _$JsonConverterTestClassFromJson(json); + + Map toJson() => _$JsonConverterTestClassToJson(this); + + Duration duration; + List durationList; + + BigInt bigInt = BigInt.parse('10000000000000000000'); + Map bigIntMap; + + TrivialNumber numberSilly; + Set numberSillySet; + + DateTime dateTime = DateTime(1981, 6, 5); +} + +@JsonSerializable( + nullable: false, + includeIfNull: false, +) +@GenericConverter() +class JsonConverterGeneric { + S item; + List itemList; + Map itemMap; + + JsonConverterGeneric(); + + factory JsonConverterGeneric.fromJson(Map json) => + _$JsonConverterGenericFromJson(json); + + Map toJson() => _$JsonConverterGenericToJson(this); +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null__non_nullable.g.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null__non_nullable.g.dart new file mode 100644 index 000000000..91ba7b1e9 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_exclude_null__non_nullable.g.dart @@ -0,0 +1,189 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'kitchen_sink.g_exclude_null__non_nullable.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +KitchenSink _$KitchenSinkFromJson(Map json) { + return KitchenSink( + ctorValidatedNo42: json['no-42'] as int, + iterable: json['iterable'] as List, + dynamicIterable: json['dynamicIterable'] as List, + objectIterable: json['objectIterable'] as List, + intIterable: (json['intIterable'] as List).map((e) => e as int), + dateTimeIterable: (json['datetime-iterable'] as List) + .map((e) => DateTime.parse(e as String)), + ) + ..dateTime = DateTime.parse(json['dateTime'] as String) + ..bigInt = BigInt.parse(json['bigInt'] as String) + ..set = (json['set'] as List).toSet() + ..dynamicSet = (json['dynamicSet'] as List).toSet() + ..objectSet = (json['objectSet'] as List).toSet() + ..intSet = (json['intSet'] as List).map((e) => e as int).toSet() + ..dateTimeSet = (json['dateTimeSet'] as List) + .map((e) => DateTime.parse(e as String)) + .toSet() + ..list = json['list'] as List + ..dynamicList = json['dynamicList'] as List + ..objectList = json['objectList'] as List + ..intList = (json['intList'] as List).map((e) => e as int).toList() + ..dateTimeList = (json['dateTimeList'] as List) + .map((e) => DateTime.parse(e as String)) + .toList() + ..map = json['map'] as Map + ..stringStringMap = Map.from(json['stringStringMap'] as Map) + ..dynamicIntMap = Map.from(json['dynamicIntMap'] as Map) + ..objectDateTimeMap = + (json['objectDateTimeMap'] as Map).map( + (k, e) => MapEntry(k, DateTime.parse(e as String)), + ) + ..crazyComplex = (json['crazyComplex'] as List) + .map((e) => (e as Map).map( + (k, e) => MapEntry( + k, + (e as Map).map( + (k, e) => MapEntry( + k, + (e as List) + .map((e) => (e as List) + .map((e) => DateTime.parse(e as String)) + .toList()) + .toList()), + )), + )) + .toList() + ..val = Map.from(json['val'] as Map) + ..writeNotNull = json['writeNotNull'] as bool + ..string = json[r'$string'] as String + ..simpleObject = + SimpleObject.fromJson(json['simpleObject'] as Map) + ..strictKeysObject = StrictKeysObject.fromJson( + json['strictKeysObject'] as Map) + ..validatedPropertyNo42 = json['validatedPropertyNo42'] as int; +} + +Map _$KitchenSinkToJson(KitchenSink instance) => + { + 'no-42': instance.ctorValidatedNo42, + 'dateTime': instance.dateTime.toIso8601String(), + 'bigInt': instance.bigInt.toString(), + 'iterable': instance.iterable.toList(), + 'dynamicIterable': instance.dynamicIterable.toList(), + 'objectIterable': instance.objectIterable.toList(), + 'intIterable': instance.intIterable.toList(), + 'set': instance.set.toList(), + 'dynamicSet': instance.dynamicSet.toList(), + 'objectSet': instance.objectSet.toList(), + 'intSet': instance.intSet.toList(), + 'dateTimeSet': + instance.dateTimeSet.map((e) => e.toIso8601String()).toList(), + 'datetime-iterable': + instance.dateTimeIterable.map((e) => e.toIso8601String()).toList(), + 'list': instance.list, + 'dynamicList': instance.dynamicList, + 'objectList': instance.objectList, + 'intList': instance.intList, + 'dateTimeList': + instance.dateTimeList.map((e) => e.toIso8601String()).toList(), + 'map': instance.map, + 'stringStringMap': instance.stringStringMap, + 'dynamicIntMap': instance.dynamicIntMap, + 'objectDateTimeMap': instance.objectDateTimeMap + .map((k, e) => MapEntry(k, e.toIso8601String())), + 'crazyComplex': instance.crazyComplex + .map((e) => e.map((k, e) => MapEntry( + k, + e.map((k, e) => MapEntry( + k, + e + .map((e) => e.map((e) => e.toIso8601String()).toList()) + .toList()))))) + .toList(), + 'val': instance.val, + 'writeNotNull': instance.writeNotNull, + r'$string': instance.string, + 'simpleObject': instance.simpleObject, + 'strictKeysObject': instance.strictKeysObject, + 'validatedPropertyNo42': instance.validatedPropertyNo42, + }; + +JsonConverterTestClass _$JsonConverterTestClassFromJson( + Map json) { + return JsonConverterTestClass() + ..duration = durationConverter.fromJson(json['duration'] as int) + ..durationList = (json['durationList'] as List) + .map((e) => durationConverter.fromJson(e as int)) + .toList() + ..bigInt = const BigIntStringConverter().fromJson(json['bigInt'] as String) + ..bigIntMap = (json['bigIntMap'] as Map).map( + (k, e) => + MapEntry(k, const BigIntStringConverter().fromJson(e as String)), + ) + ..numberSilly = + TrivialNumberConverter.instance.fromJson(json['numberSilly'] as int) + ..numberSillySet = (json['numberSillySet'] as List) + .map((e) => TrivialNumberConverter.instance.fromJson(e as int)) + .toSet() + ..dateTime = + const EpochDateTimeConverter().fromJson(json['dateTime'] as int); +} + +Map _$JsonConverterTestClassToJson( + JsonConverterTestClass instance) { + final val = {}; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('duration', durationConverter.toJson(instance.duration)); + val['durationList'] = + instance.durationList.map(durationConverter.toJson).toList(); + writeNotNull('bigInt', const BigIntStringConverter().toJson(instance.bigInt)); + val['bigIntMap'] = instance.bigIntMap + .map((k, e) => MapEntry(k, const BigIntStringConverter().toJson(e))); + writeNotNull('numberSilly', + TrivialNumberConverter.instance.toJson(instance.numberSilly)); + val['numberSillySet'] = instance.numberSillySet + .map(TrivialNumberConverter.instance.toJson) + .toList(); + writeNotNull( + 'dateTime', const EpochDateTimeConverter().toJson(instance.dateTime)); + return val; +} + +JsonConverterGeneric _$JsonConverterGenericFromJson( + Map json) { + return JsonConverterGeneric() + ..item = + GenericConverter().fromJson(json['item'] as Map) + ..itemList = (json['itemList'] as List) + .map((e) => GenericConverter().fromJson(e as Map)) + .toList() + ..itemMap = (json['itemMap'] as Map).map( + (k, e) => MapEntry( + k, GenericConverter().fromJson(e as Map)), + ); +} + +Map _$JsonConverterGenericToJson( + JsonConverterGeneric instance) { + final val = {}; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('item', GenericConverter().toJson(instance.item)); + val['itemList'] = + instance.itemList.map(GenericConverter().toJson).toList(); + val['itemMap'] = instance.itemMap + .map((k, e) => MapEntry(k, GenericConverter().toJson(e))); + return val; +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_explicit_to_json.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_explicit_to_json.dart new file mode 100644 index 000000000..5a4fbeb20 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_explicit_to_json.dart @@ -0,0 +1,199 @@ +// 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. + +// ignore_for_file: annotate_overrides, hash_and_equals +import 'package:json_annotation/json_annotation.dart'; + +import 'json_converters.dart'; +import 'kitchen_sink_interface.dart' as k; +import 'simple_object.dart'; +import 'strict_keys_object.dart'; + +part 'kitchen_sink.g_explicit_to_json.g.dart'; + +// NOTE: these methods are replaced in the `non_nullable` cases to return +// non-null values. +List _defaultList() => null; +Set _defaultSet() => null; +Map _defaultMap() => null; +SimpleObject _defaultSimpleObject() => null; +StrictKeysObject _defaultStrictKeysObject() => null; + +const k.KitchenSinkFactory factory = _Factory(); + +class _Factory implements k.KitchenSinkFactory { + const _Factory(); + + String get description => 'explicit_to_json'; + bool get anyMap => false; + bool get checked => false; + bool get nullable => true; + bool get excludeNull => false; + bool get explicitToJson => true; + + k.KitchenSink ctor({ + int ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) => + KitchenSink( + ctorValidatedNo42: ctorValidatedNo42, + iterable: iterable, + dynamicIterable: dynamicIterable, + objectIterable: objectIterable, + intIterable: intIterable, + dateTimeIterable: dateTimeIterable, + ); + + k.KitchenSink fromJson(Map json) => + KitchenSink.fromJson(json); + + k.JsonConverterTestClass jsonConverterCtor() => JsonConverterTestClass(); + + k.JsonConverterTestClass jsonConverterFromJson(Map json) => + JsonConverterTestClass.fromJson(json); +} + +@JsonSerializable( + explicitToJson: true, +) +class KitchenSink implements k.KitchenSink { + // NOTE: exposing these as Iterable, but storing the values as List + // to make the equality test work trivially. + final Iterable _iterable; + final Iterable _dynamicIterable; + final Iterable _objectIterable; + final Iterable _intIterable; + final Iterable _dateTimeIterable; + + @JsonKey(name: 'no-42') + final int ctorValidatedNo42; + + KitchenSink({ + this.ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) : _iterable = iterable?.toList() ?? _defaultList(), + _dynamicIterable = dynamicIterable?.toList() ?? _defaultList(), + _objectIterable = objectIterable?.toList() ?? _defaultList(), + _intIterable = intIterable?.toList() ?? _defaultList(), + _dateTimeIterable = dateTimeIterable?.toList() ?? _defaultList() { + if (ctorValidatedNo42 == 42) { + throw ArgumentError.value( + 42, 'ctorValidatedNo42', 'The value `42` is not allowed.'); + } + } + + factory KitchenSink.fromJson(Map json) => + _$KitchenSinkFromJson(json); + + Map toJson() => _$KitchenSinkToJson(this); + + DateTime dateTime; + + BigInt bigInt; + + Iterable get iterable => _iterable; + Iterable get dynamicIterable => _dynamicIterable; + Iterable get objectIterable => _objectIterable; + Iterable get intIterable => _intIterable; + + Set set = _defaultSet(); + Set dynamicSet = _defaultSet(); + Set objectSet = _defaultSet(); + Set intSet = _defaultSet(); + Set dateTimeSet = _defaultSet(); + + // Added a one-off annotation on a property (not a field) + @JsonKey(name: 'datetime-iterable') + Iterable get dateTimeIterable => _dateTimeIterable; + + List list = _defaultList(); + List dynamicList = _defaultList(); + List objectList = _defaultList(); + List intList = _defaultList(); + List dateTimeList = _defaultList(); + + Map map = _defaultMap(); + Map stringStringMap = _defaultMap(); + Map dynamicIntMap = _defaultMap(); + Map objectDateTimeMap = _defaultMap(); + + List>>>> crazyComplex = + _defaultList(); + + // Handle fields with names that collide with helper names + Map val = _defaultMap(); + bool writeNotNull; + @JsonKey(name: r'$string') + String string; + + SimpleObject simpleObject = _defaultSimpleObject(); + + StrictKeysObject strictKeysObject = _defaultStrictKeysObject(); + + int _validatedPropertyNo42; + int get validatedPropertyNo42 => _validatedPropertyNo42; + + set validatedPropertyNo42(int value) { + if (value == 42) { + throw StateError('Cannot be 42!'); + } + _validatedPropertyNo42 = value; + } + + bool operator ==(Object other) => k.sinkEquals(this, other); +} + +@JsonSerializable( + explicitToJson: true, +) +// referencing a top-level field should work +@durationConverter +// referencing via a const constructor should work +@BigIntStringConverter() +@TrivialNumberConverter.instance +@EpochDateTimeConverter() +class JsonConverterTestClass implements k.JsonConverterTestClass { + JsonConverterTestClass(); + + factory JsonConverterTestClass.fromJson(Map json) => + _$JsonConverterTestClassFromJson(json); + + Map toJson() => _$JsonConverterTestClassToJson(this); + + Duration duration; + List durationList; + + BigInt bigInt; + Map bigIntMap; + + TrivialNumber numberSilly; + Set numberSillySet; + + DateTime dateTime; +} + +@JsonSerializable( + explicitToJson: true, +) +@GenericConverter() +class JsonConverterGeneric { + S item; + List itemList; + Map itemMap; + + JsonConverterGeneric(); + + factory JsonConverterGeneric.fromJson(Map json) => + _$JsonConverterGenericFromJson(json); + + Map toJson() => _$JsonConverterGenericToJson(this); +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_explicit_to_json.g.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_explicit_to_json.g.dart new file mode 100644 index 000000000..353b5c35d --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_explicit_to_json.g.dart @@ -0,0 +1,187 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'kitchen_sink.g_explicit_to_json.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +KitchenSink _$KitchenSinkFromJson(Map json) { + return KitchenSink( + ctorValidatedNo42: json['no-42'] as int, + iterable: json['iterable'] as List, + dynamicIterable: json['dynamicIterable'] as List, + objectIterable: json['objectIterable'] as List, + intIterable: (json['intIterable'] as List)?.map((e) => e as int), + dateTimeIterable: (json['datetime-iterable'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)), + ) + ..dateTime = json['dateTime'] == null + ? null + : DateTime.parse(json['dateTime'] as String) + ..bigInt = + json['bigInt'] == null ? null : BigInt.parse(json['bigInt'] as String) + ..set = (json['set'] as List)?.toSet() + ..dynamicSet = (json['dynamicSet'] as List)?.toSet() + ..objectSet = (json['objectSet'] as List)?.toSet() + ..intSet = (json['intSet'] as List)?.map((e) => e as int)?.toSet() + ..dateTimeSet = (json['dateTimeSet'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)) + ?.toSet() + ..list = json['list'] as List + ..dynamicList = json['dynamicList'] as List + ..objectList = json['objectList'] as List + ..intList = (json['intList'] as List)?.map((e) => e as int)?.toList() + ..dateTimeList = (json['dateTimeList'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)) + ?.toList() + ..map = json['map'] as Map + ..stringStringMap = (json['stringStringMap'] as Map)?.map( + (k, e) => MapEntry(k, e as String), + ) + ..dynamicIntMap = (json['dynamicIntMap'] as Map)?.map( + (k, e) => MapEntry(k, e as int), + ) + ..objectDateTimeMap = + (json['objectDateTimeMap'] as Map)?.map( + (k, e) => MapEntry(k, e == null ? null : DateTime.parse(e as String)), + ) + ..crazyComplex = (json['crazyComplex'] as List) + ?.map((e) => (e as Map)?.map( + (k, e) => MapEntry( + k, + (e as Map)?.map( + (k, e) => MapEntry( + k, + (e as List) + ?.map((e) => (e as List) + ?.map((e) => e == null + ? null + : DateTime.parse(e as String)) + ?.toList()) + ?.toList()), + )), + )) + ?.toList() + ..val = (json['val'] as Map)?.map( + (k, e) => MapEntry(k, e as bool), + ) + ..writeNotNull = json['writeNotNull'] as bool + ..string = json[r'$string'] as String + ..simpleObject = json['simpleObject'] == null + ? null + : SimpleObject.fromJson(json['simpleObject'] as Map) + ..strictKeysObject = json['strictKeysObject'] == null + ? null + : StrictKeysObject.fromJson( + json['strictKeysObject'] as Map) + ..validatedPropertyNo42 = json['validatedPropertyNo42'] as int; +} + +Map _$KitchenSinkToJson(KitchenSink instance) => + { + 'no-42': instance.ctorValidatedNo42, + 'dateTime': instance.dateTime?.toIso8601String(), + 'bigInt': instance.bigInt?.toString(), + 'iterable': instance.iterable?.toList(), + 'dynamicIterable': instance.dynamicIterable?.toList(), + 'objectIterable': instance.objectIterable?.toList(), + 'intIterable': instance.intIterable?.toList(), + 'set': instance.set?.toList(), + 'dynamicSet': instance.dynamicSet?.toList(), + 'objectSet': instance.objectSet?.toList(), + 'intSet': instance.intSet?.toList(), + 'dateTimeSet': + instance.dateTimeSet?.map((e) => e?.toIso8601String())?.toList(), + 'datetime-iterable': + instance.dateTimeIterable?.map((e) => e?.toIso8601String())?.toList(), + 'list': instance.list, + 'dynamicList': instance.dynamicList, + 'objectList': instance.objectList, + 'intList': instance.intList, + 'dateTimeList': + instance.dateTimeList?.map((e) => e?.toIso8601String())?.toList(), + 'map': instance.map, + 'stringStringMap': instance.stringStringMap, + 'dynamicIntMap': instance.dynamicIntMap, + 'objectDateTimeMap': instance.objectDateTimeMap + ?.map((k, e) => MapEntry(k, e?.toIso8601String())), + 'crazyComplex': instance.crazyComplex + ?.map((e) => e?.map((k, e) => MapEntry( + k, + e?.map((k, e) => MapEntry( + k, + e + ?.map( + (e) => e?.map((e) => e?.toIso8601String())?.toList()) + ?.toList()))))) + ?.toList(), + 'val': instance.val, + 'writeNotNull': instance.writeNotNull, + r'$string': instance.string, + 'simpleObject': instance.simpleObject?.toJson(), + 'strictKeysObject': instance.strictKeysObject?.toJson(), + 'validatedPropertyNo42': instance.validatedPropertyNo42, + }; + +JsonConverterTestClass _$JsonConverterTestClassFromJson( + Map json) { + return JsonConverterTestClass() + ..duration = durationConverter.fromJson(json['duration'] as int) + ..durationList = (json['durationList'] as List) + ?.map((e) => durationConverter.fromJson(e as int)) + ?.toList() + ..bigInt = const BigIntStringConverter().fromJson(json['bigInt'] as String) + ..bigIntMap = (json['bigIntMap'] as Map)?.map( + (k, e) => + MapEntry(k, const BigIntStringConverter().fromJson(e as String)), + ) + ..numberSilly = + TrivialNumberConverter.instance.fromJson(json['numberSilly'] as int) + ..numberSillySet = (json['numberSillySet'] as List) + ?.map((e) => TrivialNumberConverter.instance.fromJson(e as int)) + ?.toSet() + ..dateTime = + const EpochDateTimeConverter().fromJson(json['dateTime'] as int); +} + +Map _$JsonConverterTestClassToJson( + JsonConverterTestClass instance) => + { + 'duration': durationConverter.toJson(instance.duration), + 'durationList': + instance.durationList?.map(durationConverter.toJson)?.toList(), + 'bigInt': const BigIntStringConverter().toJson(instance.bigInt), + 'bigIntMap': instance.bigIntMap + ?.map((k, e) => MapEntry(k, const BigIntStringConverter().toJson(e))), + 'numberSilly': + TrivialNumberConverter.instance.toJson(instance.numberSilly), + 'numberSillySet': instance.numberSillySet + ?.map(TrivialNumberConverter.instance.toJson) + ?.toList(), + 'dateTime': const EpochDateTimeConverter().toJson(instance.dateTime), + }; + +JsonConverterGeneric _$JsonConverterGenericFromJson( + Map json) { + return JsonConverterGeneric() + ..item = + GenericConverter().fromJson(json['item'] as Map) + ..itemList = (json['itemList'] as List) + ?.map((e) => GenericConverter().fromJson(e as Map)) + ?.toList() + ..itemMap = (json['itemMap'] as Map)?.map( + (k, e) => MapEntry( + k, GenericConverter().fromJson(e as Map)), + ); +} + +Map _$JsonConverterGenericToJson( + JsonConverterGeneric instance) => + { + 'item': GenericConverter().toJson(instance.item), + 'itemList': + instance.itemList?.map(GenericConverter().toJson)?.toList(), + 'itemMap': instance.itemMap + ?.map((k, e) => MapEntry(k, GenericConverter().toJson(e))), + }; diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_non_nullable.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_non_nullable.dart new file mode 100644 index 000000000..71d5919c4 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_non_nullable.dart @@ -0,0 +1,199 @@ +// 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. + +// ignore_for_file: annotate_overrides, hash_and_equals +import 'package:json_annotation/json_annotation.dart'; + +import 'json_converters.dart'; +import 'kitchen_sink_interface.dart' as k; +import 'simple_object.dart'; +import 'strict_keys_object.dart'; + +part 'kitchen_sink.g_non_nullable.g.dart'; + +// NOTE: these methods are replaced in the `non_nullable` cases to return +// non-null values. +List _defaultList() => []; +Set _defaultSet() => {}; +Map _defaultMap() => {}; +SimpleObject _defaultSimpleObject() => SimpleObject(42); +StrictKeysObject _defaultStrictKeysObject() => StrictKeysObject(10, 'cool'); + +const k.KitchenSinkFactory factory = _Factory(); + +class _Factory implements k.KitchenSinkFactory { + const _Factory(); + + String get description => 'non_nullable'; + bool get anyMap => false; + bool get checked => false; + bool get nullable => false; + bool get excludeNull => false; + bool get explicitToJson => false; + + k.KitchenSink ctor({ + int ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) => + KitchenSink( + ctorValidatedNo42: ctorValidatedNo42, + iterable: iterable, + dynamicIterable: dynamicIterable, + objectIterable: objectIterable, + intIterable: intIterable, + dateTimeIterable: dateTimeIterable, + ); + + k.KitchenSink fromJson(Map json) => + KitchenSink.fromJson(json); + + k.JsonConverterTestClass jsonConverterCtor() => JsonConverterTestClass(); + + k.JsonConverterTestClass jsonConverterFromJson(Map json) => + JsonConverterTestClass.fromJson(json); +} + +@JsonSerializable( + nullable: false, +) +class KitchenSink implements k.KitchenSink { + // NOTE: exposing these as Iterable, but storing the values as List + // to make the equality test work trivially. + final Iterable _iterable; + final Iterable _dynamicIterable; + final Iterable _objectIterable; + final Iterable _intIterable; + final Iterable _dateTimeIterable; + + @JsonKey(name: 'no-42') + final int ctorValidatedNo42; + + KitchenSink({ + this.ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }) : _iterable = iterable?.toList() ?? _defaultList(), + _dynamicIterable = dynamicIterable?.toList() ?? _defaultList(), + _objectIterable = objectIterable?.toList() ?? _defaultList(), + _intIterable = intIterable?.toList() ?? _defaultList(), + _dateTimeIterable = dateTimeIterable?.toList() ?? _defaultList() { + if (ctorValidatedNo42 == 42) { + throw ArgumentError.value( + 42, 'ctorValidatedNo42', 'The value `42` is not allowed.'); + } + } + + factory KitchenSink.fromJson(Map json) => + _$KitchenSinkFromJson(json); + + Map toJson() => _$KitchenSinkToJson(this); + + DateTime dateTime = DateTime(1981, 6, 5); + + BigInt bigInt = BigInt.parse('10000000000000000000'); + + Iterable get iterable => _iterable; + Iterable get dynamicIterable => _dynamicIterable; + Iterable get objectIterable => _objectIterable; + Iterable get intIterable => _intIterable; + + Set set = _defaultSet(); + Set dynamicSet = _defaultSet(); + Set objectSet = _defaultSet(); + Set intSet = _defaultSet(); + Set dateTimeSet = _defaultSet(); + + // Added a one-off annotation on a property (not a field) + @JsonKey(name: 'datetime-iterable') + Iterable get dateTimeIterable => _dateTimeIterable; + + List list = _defaultList(); + List dynamicList = _defaultList(); + List objectList = _defaultList(); + List intList = _defaultList(); + List dateTimeList = _defaultList(); + + Map map = _defaultMap(); + Map stringStringMap = _defaultMap(); + Map dynamicIntMap = _defaultMap(); + Map objectDateTimeMap = _defaultMap(); + + List>>>> crazyComplex = + _defaultList(); + + // Handle fields with names that collide with helper names + Map val = _defaultMap(); + bool writeNotNull; + @JsonKey(name: r'$string') + String string; + + SimpleObject simpleObject = _defaultSimpleObject(); + + StrictKeysObject strictKeysObject = _defaultStrictKeysObject(); + + int _validatedPropertyNo42; + int get validatedPropertyNo42 => _validatedPropertyNo42; + + set validatedPropertyNo42(int value) { + if (value == 42) { + throw StateError('Cannot be 42!'); + } + _validatedPropertyNo42 = value; + } + + bool operator ==(Object other) => k.sinkEquals(this, other); +} + +@JsonSerializable( + nullable: false, +) +// referencing a top-level field should work +@durationConverter +// referencing via a const constructor should work +@BigIntStringConverter() +@TrivialNumberConverter.instance +@EpochDateTimeConverter() +class JsonConverterTestClass implements k.JsonConverterTestClass { + JsonConverterTestClass(); + + factory JsonConverterTestClass.fromJson(Map json) => + _$JsonConverterTestClassFromJson(json); + + Map toJson() => _$JsonConverterTestClassToJson(this); + + Duration duration; + List durationList; + + BigInt bigInt = BigInt.parse('10000000000000000000'); + Map bigIntMap; + + TrivialNumber numberSilly; + Set numberSillySet; + + DateTime dateTime = DateTime(1981, 6, 5); +} + +@JsonSerializable( + nullable: false, +) +@GenericConverter() +class JsonConverterGeneric { + S item; + List itemList; + Map itemMap; + + JsonConverterGeneric(); + + factory JsonConverterGeneric.fromJson(Map json) => + _$JsonConverterGenericFromJson(json); + + Map toJson() => _$JsonConverterGenericToJson(this); +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_non_nullable.g.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_non_nullable.g.dart new file mode 100644 index 000000000..2c85c5a13 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink.g_non_nullable.g.dart @@ -0,0 +1,171 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'kitchen_sink.g_non_nullable.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +KitchenSink _$KitchenSinkFromJson(Map json) { + return KitchenSink( + ctorValidatedNo42: json['no-42'] as int, + iterable: json['iterable'] as List, + dynamicIterable: json['dynamicIterable'] as List, + objectIterable: json['objectIterable'] as List, + intIterable: (json['intIterable'] as List).map((e) => e as int), + dateTimeIterable: (json['datetime-iterable'] as List) + .map((e) => DateTime.parse(e as String)), + ) + ..dateTime = DateTime.parse(json['dateTime'] as String) + ..bigInt = BigInt.parse(json['bigInt'] as String) + ..set = (json['set'] as List).toSet() + ..dynamicSet = (json['dynamicSet'] as List).toSet() + ..objectSet = (json['objectSet'] as List).toSet() + ..intSet = (json['intSet'] as List).map((e) => e as int).toSet() + ..dateTimeSet = (json['dateTimeSet'] as List) + .map((e) => DateTime.parse(e as String)) + .toSet() + ..list = json['list'] as List + ..dynamicList = json['dynamicList'] as List + ..objectList = json['objectList'] as List + ..intList = (json['intList'] as List).map((e) => e as int).toList() + ..dateTimeList = (json['dateTimeList'] as List) + .map((e) => DateTime.parse(e as String)) + .toList() + ..map = json['map'] as Map + ..stringStringMap = Map.from(json['stringStringMap'] as Map) + ..dynamicIntMap = Map.from(json['dynamicIntMap'] as Map) + ..objectDateTimeMap = + (json['objectDateTimeMap'] as Map).map( + (k, e) => MapEntry(k, DateTime.parse(e as String)), + ) + ..crazyComplex = (json['crazyComplex'] as List) + .map((e) => (e as Map).map( + (k, e) => MapEntry( + k, + (e as Map).map( + (k, e) => MapEntry( + k, + (e as List) + .map((e) => (e as List) + .map((e) => DateTime.parse(e as String)) + .toList()) + .toList()), + )), + )) + .toList() + ..val = Map.from(json['val'] as Map) + ..writeNotNull = json['writeNotNull'] as bool + ..string = json[r'$string'] as String + ..simpleObject = + SimpleObject.fromJson(json['simpleObject'] as Map) + ..strictKeysObject = StrictKeysObject.fromJson( + json['strictKeysObject'] as Map) + ..validatedPropertyNo42 = json['validatedPropertyNo42'] as int; +} + +Map _$KitchenSinkToJson(KitchenSink instance) => + { + 'no-42': instance.ctorValidatedNo42, + 'dateTime': instance.dateTime.toIso8601String(), + 'bigInt': instance.bigInt.toString(), + 'iterable': instance.iterable.toList(), + 'dynamicIterable': instance.dynamicIterable.toList(), + 'objectIterable': instance.objectIterable.toList(), + 'intIterable': instance.intIterable.toList(), + 'set': instance.set.toList(), + 'dynamicSet': instance.dynamicSet.toList(), + 'objectSet': instance.objectSet.toList(), + 'intSet': instance.intSet.toList(), + 'dateTimeSet': + instance.dateTimeSet.map((e) => e.toIso8601String()).toList(), + 'datetime-iterable': + instance.dateTimeIterable.map((e) => e.toIso8601String()).toList(), + 'list': instance.list, + 'dynamicList': instance.dynamicList, + 'objectList': instance.objectList, + 'intList': instance.intList, + 'dateTimeList': + instance.dateTimeList.map((e) => e.toIso8601String()).toList(), + 'map': instance.map, + 'stringStringMap': instance.stringStringMap, + 'dynamicIntMap': instance.dynamicIntMap, + 'objectDateTimeMap': instance.objectDateTimeMap + .map((k, e) => MapEntry(k, e.toIso8601String())), + 'crazyComplex': instance.crazyComplex + .map((e) => e.map((k, e) => MapEntry( + k, + e.map((k, e) => MapEntry( + k, + e + .map((e) => e.map((e) => e.toIso8601String()).toList()) + .toList()))))) + .toList(), + 'val': instance.val, + 'writeNotNull': instance.writeNotNull, + r'$string': instance.string, + 'simpleObject': instance.simpleObject, + 'strictKeysObject': instance.strictKeysObject, + 'validatedPropertyNo42': instance.validatedPropertyNo42, + }; + +JsonConverterTestClass _$JsonConverterTestClassFromJson( + Map json) { + return JsonConverterTestClass() + ..duration = durationConverter.fromJson(json['duration'] as int) + ..durationList = (json['durationList'] as List) + .map((e) => durationConverter.fromJson(e as int)) + .toList() + ..bigInt = const BigIntStringConverter().fromJson(json['bigInt'] as String) + ..bigIntMap = (json['bigIntMap'] as Map).map( + (k, e) => + MapEntry(k, const BigIntStringConverter().fromJson(e as String)), + ) + ..numberSilly = + TrivialNumberConverter.instance.fromJson(json['numberSilly'] as int) + ..numberSillySet = (json['numberSillySet'] as List) + .map((e) => TrivialNumberConverter.instance.fromJson(e as int)) + .toSet() + ..dateTime = + const EpochDateTimeConverter().fromJson(json['dateTime'] as int); +} + +Map _$JsonConverterTestClassToJson( + JsonConverterTestClass instance) => + { + 'duration': durationConverter.toJson(instance.duration), + 'durationList': + instance.durationList.map(durationConverter.toJson).toList(), + 'bigInt': const BigIntStringConverter().toJson(instance.bigInt), + 'bigIntMap': instance.bigIntMap + .map((k, e) => MapEntry(k, const BigIntStringConverter().toJson(e))), + 'numberSilly': + TrivialNumberConverter.instance.toJson(instance.numberSilly), + 'numberSillySet': instance.numberSillySet + .map(TrivialNumberConverter.instance.toJson) + .toList(), + 'dateTime': const EpochDateTimeConverter().toJson(instance.dateTime), + }; + +JsonConverterGeneric _$JsonConverterGenericFromJson( + Map json) { + return JsonConverterGeneric() + ..item = + GenericConverter().fromJson(json['item'] as Map) + ..itemList = (json['itemList'] as List) + .map((e) => GenericConverter().fromJson(e as Map)) + .toList() + ..itemMap = (json['itemMap'] as Map).map( + (k, e) => MapEntry( + k, GenericConverter().fromJson(e as Map)), + ); +} + +Map _$JsonConverterGenericToJson( + JsonConverterGeneric instance) => + { + 'item': GenericConverter().toJson(instance.item), + 'itemList': instance.itemList.map(GenericConverter().toJson).toList(), + 'itemMap': instance.itemMap + .map((k, e) => MapEntry(k, GenericConverter().toJson(e))), + }; diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink_interface.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink_interface.dart new file mode 100644 index 000000000..93916afac --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink_interface.dart @@ -0,0 +1,106 @@ +// Copyright (c) 2017, 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. + +import 'package:collection/collection.dart'; +import 'simple_object.dart'; + +abstract class KitchenSinkFactory { + String get description; + bool get anyMap; + bool get checked; + bool get nullable; + bool get excludeNull; + bool get explicitToJson; + + KitchenSink ctor({ + int ctorValidatedNo42, + Iterable iterable, + Iterable dynamicIterable, + Iterable objectIterable, + Iterable intIterable, + Iterable dateTimeIterable, + }); + + KitchenSink fromJson(Map json); + + JsonConverterTestClass jsonConverterCtor(); + + JsonConverterTestClass jsonConverterFromJson(Map json); + + @override + String toString() => description; +} + +abstract class JsonConverterTestClass { + Map toJson(); +} + +abstract class KitchenSink { + int get ctorValidatedNo42; + DateTime dateTime; + BigInt bigInt; + + Iterable get iterable; + Iterable get dynamicIterable; + Iterable get objectIterable; + Iterable get intIterable; + + Iterable get dateTimeIterable; + + List list; + List dynamicList; + List objectList; + List intList; + List dateTimeList; + + Set set; + Set dynamicSet; + Set objectSet; + Set intSet; + Set dateTimeSet; + + Map map; + Map stringStringMap; + Map dynamicIntMap; + Map objectDateTimeMap; + + List>>>> crazyComplex; + + Map val; + bool writeNotNull; + String string; + + SimpleObject get simpleObject; + + int validatedPropertyNo42; + + Map toJson(); +} + +// TODO: finish this... +bool sinkEquals(KitchenSink a, Object other) => + other is KitchenSink && + a.ctorValidatedNo42 == other.ctorValidatedNo42 && + a.dateTime == other.dateTime && + _deepEquals(a.iterable, other.iterable) && + _deepEquals(a.dynamicIterable, other.dynamicIterable) && + // objectIterable + // intIterable + _deepEquals(a.dateTimeIterable, other.dateTimeIterable) && + // list + // dynamicList + // objectList + // intList + _deepEquals(a.dateTimeList, other.dateTimeList) && + // map + // stringStringMap + // stringIntMap + _deepEquals(a.objectDateTimeMap, other.objectDateTimeMap) && + _deepEquals(a.crazyComplex, other.crazyComplex) && + // val + a.writeNotNull == other.writeNotNull && + a.string == other.string; + +bool _deepEquals(Object a, Object b) => + const DeepCollectionEquality().equals(a, b); diff --git a/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink_test.dart b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink_test.dart new file mode 100644 index 000000000..86a0330a6 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/kitchen_sink_test.dart @@ -0,0 +1,430 @@ +// Copyright (c) 2015, 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. + +import 'package:json_annotation/json_annotation.dart'; +import 'package:test/test.dart'; +import 'package:yaml/yaml.dart'; + +import '../test_utils.dart'; +import 'kitchen_sink.factories.dart'; +import 'kitchen_sink_interface.dart'; +import 'strict_keys_object.dart'; + +// copied and renamed as private from /lib/src/constants.dart +const _generatedLocalVarName = 'val'; +const _toJsonMapHelperName = 'writeNotNull'; + +final _isATypeError = isA(); + +// ignore: deprecated_member_use +final _isACastError = isA(); + +Matcher _isAUnrecognizedKeysException(expectedMessage) => + isA() + .having((e) => e.message, 'message', expectedMessage); + +Matcher _isMissingKeyException(expectedMessage) => + isA() + .having((e) => e.message, 'message', expectedMessage); + +void main() { + test('valid values covers all keys', () { + expect(_invalidValueTypes.keys, orderedEquals(_validValues.keys)); + }); + + test('tracking Map/Iterable types correctly', () { + for (var entry in _validValues.entries) { + if (_iterableMapKeys.contains(entry.key) || + _encodedAsMapKeys.contains(entry.key)) { + expect(entry.value, anyOf(isMap, isList)); + } else { + expect(entry.value, isNot(anyOf(isMap, isList))); + } + } + }); + + test('required keys', () { + expect( + () => StrictKeysObject.fromJson({}), + throwsA(_isMissingKeyException( + 'Required keys are missing: value, custom_field.'))); + }); + + for (var factory in factories) { + group(factory.description, () { + if (factory.nullable) { + _nullableTests(factory); + } else { + _nonNullableTests(factory); + } + if (factory.anyMap) { + _anyMapTests(factory); + } + _sharedTests(factory); + }); + } +} + +const _jsonConverterValidValues = { + 'duration': 5, + 'durationList': [5], + 'bigInt': '5', + 'bigIntMap': {'vaule': '5'}, + 'numberSilly': 5, + 'numberSillySet': [5], + 'dateTime': 5 +}; + +void _nonNullableTests(KitchenSinkFactory factory) { + test('with null values fails serialization', () { + expect(() => (factory.ctor()..objectDateTimeMap = null).toJson(), + throwsNoSuchMethodError); + }); + + test('with empty json fails deserialization', () { + Matcher matcher; + if (factory.checked) { + matcher = _checkedMatcher('intIterable'); + } else { + matcher = isNoSuchMethodError; + } + expect(() => factory.fromJson({}), throwsA(matcher)); + }); + + test('nullable values are not allowed in non-nullable version', () { + var instance = factory.jsonConverterCtor(); + expect(() => instance.toJson(), throwsNoSuchMethodError, + reason: 'Trying to call `map` on a null list'); + + instance = factory.jsonConverterFromJson(_jsonConverterValidValues); + final json = instance.toJson(); + expect(json, _jsonConverterValidValues); + expect(json.values, everyElement(isNotNull)); + + final instance2 = factory.jsonConverterFromJson(json); + expect(instance2.toJson(), json); + }); +} + +void _nullableTests(KitchenSinkFactory factory) { + void roundTripSink(KitchenSink p) { + roundTripObject(p, factory.fromJson); + } + + test('nullable values are allowed in the nullable version', () { + final instance = factory.jsonConverterCtor(); + final json = instance.toJson(); + + if (factory.excludeNull) { + expect(json, isEmpty); + } else { + expect(json.values, everyElement(isNull)); + expect(json.keys, unorderedEquals(_jsonConverterValidValues.keys)); + + final instance2 = factory.jsonConverterFromJson(json); + expect(instance2.toJson(), json); + } + }); + + test('Fields with `!includeIfNull` should not be included when null', () { + final item = factory.ctor(); + final encoded = item.toJson(); + + if (factory.excludeNull) { + expect(encoded, isEmpty); + } else { + expect(encoded.keys, orderedEquals(_validValues.keys)); + + for (final key in _validValues.keys) { + expect(encoded, containsPair(key, isNull)); + } + } + }); + + test('list and map of DateTime', () { + final now = DateTime.now(); + final item = factory.ctor(dateTimeIterable: [now]) + ..dateTimeList = [now, null] + ..objectDateTimeMap = {'value': now, 'null': null}; + + roundTripSink(item); + }); + + test('complex nested type', () { + final item = factory.ctor() + ..crazyComplex = [ + null, + {}, + { + 'null': null, + 'empty': {}, + 'items': { + 'null': null, + 'empty': [], + 'items': [ + null, + [], + [DateTime.now()] + ] + } + } + ]; + roundTripSink(item); + }); +} + +void _anyMapTests(KitchenSinkFactory factory) { + test('valid values round-trip - yaml', () { + final jsonEncoded = loudEncode(_validValues); + final yaml = loadYaml(jsonEncoded, sourceUrl: Uri.parse('input.yaml')); + expect(jsonEncoded, loudEncode(factory.fromJson(yaml as YamlMap))); + }); + + group('a bad value for', () { + for (final e in _invalidValueTypes.entries) { + _testBadValue(e.key, e.value, factory, false); + } + for (final e in _invalidCheckedValues.entries) { + _testBadValue(e.key, e.value, factory, true); + } + }); +} + +void _sharedTests(KitchenSinkFactory factory) { + test('empty', () { + final item = factory.ctor(); + roundTripObject(item, factory.fromJson); + }); + + test('list and map of DateTime - not null', () { + final now = DateTime.now(); + final item = factory.ctor(dateTimeIterable: [now]) + ..dateTimeList = [now, now] + ..objectDateTimeMap = {'value': now}; + + roundTripObject(item, factory.fromJson); + }); + + test('complex nested type - not null', () { + final item = factory.ctor() + ..crazyComplex = [ + {}, + { + 'empty': {}, + 'items': { + 'empty': [], + 'items': [ + [], + [DateTime.now()] + ] + } + } + ]; + roundTripObject(item, factory.fromJson); + }); + + test('round trip valid, empty values', () { + final values = Map.fromEntries(_validValues.entries.map((e) { + var value = e.value; + if (_iterableMapKeys.contains(e.key)) { + if (value is List) { + value = []; + } else { + assert(value is Map); + value = {}; + } + } + return MapEntry(e.key, value); + })); + + final validInstance = factory.fromJson(values); + + roundTripObject(validInstance, factory.fromJson); + }); + + test('JSON keys should be defined in field/property order', () { + final json = factory.ctor().toJson(); + if (factory.excludeNull && factory.nullable) { + expect(json.keys, isEmpty); + } else { + expect(json.keys, orderedEquals(_validValues.keys)); + } + }); + + test('valid values round-trip - json', () { + final validInstance = factory.fromJson(_validValues); + roundTripObject(validInstance, factory.fromJson); + }); +} + +void _testBadValue(String key, Object badValue, KitchenSinkFactory factory, + bool checkedAssignment) { + final matcher = _getMatcher(factory.checked, key, checkedAssignment); + + for (final isJson in [true, false]) { + test('`$key` fails with value `$badValue`- ${isJson ? 'json' : 'yaml'}', + () { + var copy = Map.from(_validValues); + copy[key] = badValue; + + if (!isJson) { + copy = loadYaml(loudEncode(copy)) as YamlMap; + } + + expect(() => factory.fromJson(copy), matcher); + }); + } +} + +Matcher _checkedMatcher(String expectedKey) => isA() + .having((e) => e.className, 'className', 'KitchenSink') + .having((e) => e.key, 'key', expectedKey); + +Matcher _getMatcher(bool checked, String expectedKey, bool checkedAssignment) { + Matcher innerMatcher; + + if (checked) { + if (checkedAssignment && + const ['intIterable', 'datetime-iterable'].contains(expectedKey)) { + expectedKey = null; + } + + innerMatcher = _checkedMatcher(expectedKey); + } else { + innerMatcher = anyOf( + _isACastError, + _isATypeError, + _isAUnrecognizedKeysException( + 'Unrecognized keys: [invalid_key]; supported keys: ' + '[value, custom_field]', + ), + ); + + if (checkedAssignment) { + switch (expectedKey) { + case 'validatedPropertyNo42': + innerMatcher = isStateError; + break; + case 'no-42': + innerMatcher = isArgumentError; + break; + case 'strictKeysObject': + innerMatcher = _isAUnrecognizedKeysException('bob'); + break; + case 'intIterable': + case 'datetime-iterable': + innerMatcher = _isACastError; + break; + default: + throw StateError('Not expected! - $expectedKey'); + } + } + } + + return throwsA(innerMatcher); +} + +const _validValues = { + 'no-42': 0, + 'dateTime': '2018-05-10T14:20:58.927', + 'bigInt': '10000000000000000000', + 'iterable': [true], + 'dynamicIterable': [true], + 'objectIterable': [true], + 'intIterable': [42], + 'set': [true], + 'dynamicSet': [true], + 'objectSet': [true], + 'intSet': [42], + 'dateTimeSet': ['2018-05-10T14:20:58.927'], + 'datetime-iterable': ['2018-05-10T14:20:58.927'], + 'list': [true], + 'dynamicList': [true], + 'objectList': [true], + 'intList': [42], + 'dateTimeList': ['2018-05-10T14:20:58.927'], + 'map': {'key': true}, + 'stringStringMap': {'key': 'vaule'}, + 'dynamicIntMap': {'key': 42}, + 'objectDateTimeMap': {'key': '2018-05-10T14:20:58.927'}, + 'crazyComplex': [{}], + _generatedLocalVarName: {'key': true}, + _toJsonMapHelperName: true, + r'$string': 'string', + 'simpleObject': {'value': 42}, + 'strictKeysObject': {'value': 10, 'custom_field': 'cool'}, + 'validatedPropertyNo42': 0 +}; + +const _invalidValueTypes = { + 'no-42': true, + 'dateTime': true, + 'bigInt': true, + 'iterable': true, + 'dynamicIterable': true, + 'objectIterable': true, + 'intIterable': true, + 'set': true, + 'dynamicSet': true, + 'objectSet': true, + 'intSet': true, + 'dateTimeSet': true, + 'datetime-iterable': true, + 'list': true, + 'dynamicList': true, + 'objectList': true, + 'intList': [true], + 'dateTimeList': [true], + 'map': true, + 'stringStringMap': {'key': 42}, + 'dynamicIntMap': {'key': 'value'}, + 'objectDateTimeMap': {'key': 42}, + 'crazyComplex': [true], + _generatedLocalVarName: {'key': 42}, + _toJsonMapHelperName: 42, + r'$string': true, + 'simpleObject': 42, + 'strictKeysObject': { + 'value': 10, + 'invalid_key': true, + }, + 'validatedPropertyNo42': true +}; + +/// Invalid values that are found after the property set or ctor call +const _invalidCheckedValues = { + 'no-42': 42, + 'validatedPropertyNo42': 42, + 'intIterable': [true], + 'datetime-iterable': [true], +}; + +const _encodedAsMapKeys = ['simpleObject', 'strictKeysObject']; + +const _iterableMapKeys = [ + 'bigIntMap', + 'crazyComplex', + 'datetime-iterable', + 'dateTimeList', + 'dateTimeSet', + 'durationList', + 'dynamicIntMap', + 'dynamicIterable', + 'dynamicList', + 'dynamicSet', + 'intIterable', + 'intList', + 'intSet', + 'iterable', + 'list', + 'map', + 'numberSillySet', + 'objectDateTimeMap', + 'objectIterable', + 'objectList', + 'objectSet', + 'set', + 'stringStringMap', + _generatedLocalVarName, +]; diff --git a/json_serializable-3.5.2/test/kitchen_sink/simple_object.dart b/json_serializable-3.5.2/test/kitchen_sink/simple_object.dart new file mode 100644 index 000000000..c02cefc31 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/simple_object.dart @@ -0,0 +1,18 @@ +// 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'simple_object.g.dart'; + +@JsonSerializable(anyMap: true) +class SimpleObject { + final int value; + + SimpleObject(this.value); + + factory SimpleObject.fromJson(Map json) => _$SimpleObjectFromJson(json); + + Map toJson() => _$SimpleObjectToJson(this); +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/simple_object.g.dart b/json_serializable-3.5.2/test/kitchen_sink/simple_object.g.dart new file mode 100644 index 000000000..42d584b69 --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/simple_object.g.dart @@ -0,0 +1,18 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'simple_object.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleObject _$SimpleObjectFromJson(Map json) { + return SimpleObject( + json['value'] as int, + ); +} + +Map _$SimpleObjectToJson(SimpleObject instance) => + { + 'value': instance.value, + }; diff --git a/json_serializable-3.5.2/test/kitchen_sink/strict_keys_object.dart b/json_serializable-3.5.2/test/kitchen_sink/strict_keys_object.dart new file mode 100644 index 000000000..757f3eb5c --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/strict_keys_object.dart @@ -0,0 +1,23 @@ +// 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'strict_keys_object.g.dart'; + +@JsonSerializable(disallowUnrecognizedKeys: true, anyMap: true) +class StrictKeysObject { + @JsonKey(required: true) + final int value; + + @JsonKey(name: 'custom_field', required: true) + final String customField; + + StrictKeysObject(this.value, this.customField); + + factory StrictKeysObject.fromJson(Map json) => + _$StrictKeysObjectFromJson(json); + + Map toJson() => _$StrictKeysObjectToJson(this); +} diff --git a/json_serializable-3.5.2/test/kitchen_sink/strict_keys_object.g.dart b/json_serializable-3.5.2/test/kitchen_sink/strict_keys_object.g.dart new file mode 100644 index 000000000..dfdda8eaa --- /dev/null +++ b/json_serializable-3.5.2/test/kitchen_sink/strict_keys_object.g.dart @@ -0,0 +1,23 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'strict_keys_object.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +StrictKeysObject _$StrictKeysObjectFromJson(Map json) { + $checkKeys(json, + allowedKeys: const ['value', 'custom_field'], + requiredKeys: const ['value', 'custom_field']); + return StrictKeysObject( + json['value'] as int, + json['custom_field'] as String, + ); +} + +Map _$StrictKeysObjectToJson(StrictKeysObject instance) => + { + 'value': instance.value, + 'custom_field': instance.customField, + }; diff --git a/json_serializable-3.5.2/test/literal/big-list-of-naughty-strings.json b/json_serializable-3.5.2/test/literal/big-list-of-naughty-strings.json new file mode 100644 index 000000000..6fcf2777a --- /dev/null +++ b/json_serializable-3.5.2/test/literal/big-list-of-naughty-strings.json @@ -0,0 +1,509 @@ +[ + "", + "undefined", + "undef", + "null", + "NULL", + "(null)", + "nil", + "NIL", + "true", + "false", + "True", + "False", + "TRUE", + "FALSE", + "None", + "hasOwnProperty", + "\\", + "\\\\", + "0", + "1", + "1.00", + "$1.00", + "1/2", + "1E2", + "1E02", + "1E+02", + "-1", + "-1.00", + "-$1.00", + "-1/2", + "-1E2", + "-1E02", + "-1E+02", + "1/0", + "0/0", + "-2147483648/-1", + "-9223372036854775808/-1", + "-0", + "-0.0", + "+0", + "+0.0", + "0.00", + "0..0", + ".", + "0.0.0", + "0,00", + "0,,0", + ",", + "0,0,0", + "0.0/0", + "1.0/0.0", + "0.0/0.0", + "1,0/0,0", + "0,0/0,0", + "--1", + "-", + "-.", + "-,", + "999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "NaN", + "Infinity", + "-Infinity", + "INF", + "1#INF", + "-1#IND", + "1#QNAN", + "1#SNAN", + "1#IND", + "0x0", + "0xffffffff", + "0xffffffffffffffff", + "0xabad1dea", + "123456789012345678901234567890123456789", + "1,000.00", + "1 000.00", + "1'000.00", + "1,000,000.00", + "1 000 000.00", + "1'000'000.00", + "1.000,00", + "1 000,00", + "1'000,00", + "1.000.000,00", + "1 000 000,00", + "1'000'000,00", + "01000", + "08", + "09", + "2.2250738585072011e-308", + ",./;'[]\\-=", + "<>?:\"{}|_+", + "!@#$%^&*()`~", + "\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f", + "€‚ƒ„†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ", + "\t\u000b\f …             ​

   ", + "­؀؁؂؃؄؅؜۝܏᠎​‌‍‎‏‪‫‬‭‮⁠⁡⁢⁣⁤⁦⁧⁨⁩𑂽𛲠𛲡𛲢𛲣𝅳𝅴𝅵𝅶𝅷𝅸𝅹𝅺󠀁󠀠󠀡󠀢󠀣󠀤󠀥󠀦󠀧󠀨󠀩󠀪󠀫󠀬󠀭󠀮󠀯󠀰󠀱󠀲󠀳󠀴󠀵󠀶󠀷󠀸󠀹󠀺󠀻󠀼󠀽󠀾󠀿󠁀󠁁󠁂󠁃󠁄󠁅󠁆󠁇󠁈󠁉󠁊󠁋󠁌󠁍󠁎󠁏󠁐󠁑󠁒󠁓󠁔󠁕󠁖󠁗󠁘󠁙󠁚󠁛󠁜󠁝󠁞󠁟󠁠󠁡󠁢󠁣󠁤󠁥󠁦󠁧󠁨󠁩󠁪󠁫󠁬󠁭󠁮󠁯󠁰󠁱󠁲󠁳󠁴󠁵󠁶󠁷󠁸󠁹󠁺󠁻󠁼󠁽󠁾󠁿", + "", + "￾", + "Ω≈ç√∫˜µ≤≥÷", + "åß∂ƒ©˙∆˚¬…æ", + "œ∑´®†¥¨ˆøπ“‘", + "¡™£¢∞§¶•ªº–≠", + "¸˛Ç◊ı˜Â¯˘¿", + "ÅÍÎÏ˝ÓÔÒÚÆ☃", + "Œ„´‰ˇÁ¨ˆØ∏”’", + "`⁄€‹›fifl‡°·‚—±", + "⅛⅜⅝⅞", + "ЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя", + "٠١٢٣٤٥٦٧٨٩", + "⁰⁴⁵", + "₀₁₂", + "⁰⁴⁵₀₁₂", + "ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็ ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็ ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็", + "'", + "\"", + "''", + "\"\"", + "'\"'", + "\"''''\"'\"", + "\"'\"'\"''''\"", + "", + "", + "", + "", + "田中さんにあげて下さい", + "パーティーへ行かないか", + "和製漢語", + "部落格", + "사회과학원 어학연구소", + "찦차를 타고 온 펲시맨과 쑛다리 똠방각하", + "社會科學院語學研究所", + "울란바토르", + "𠜎𠜱𠝹𠱓𠱸𠲖𠳏", + "Ⱥ", + "Ⱦ", + "ヽ༼ຈل͜ຈ༽ノ ヽ༼ຈل͜ຈ༽ノ ", + "(。◕ ∀ ◕。)", + "`ィ(´∀`∩", + "__ロ(,_,*)", + "・( ̄∀ ̄)・:*:", + "゚・✿ヾ╲(。◕‿◕。)╱✿・゚", + ",。・:*:・゜’( ☻ ω ☻ )。・:*:・゜’", + "(╯°□°)╯︵ ┻━┻)", + "(ノಥ益ಥ)ノ ┻━┻", + "┬─┬ノ( º _ ºノ)", + "( ͡° ͜ʖ ͡°)", + "😍", + "👩🏽", + "👾 🙇 💁 🙅 🙆 🙋 🙎 🙍", + "🐵 🙈 🙉 🙊", + "❤️ 💔 💌 💕 💞 💓 💗 💖 💘 💝 💟 💜 💛 💚 💙", + "✋🏿 💪🏿 👐🏿 🙌🏿 👏🏿 🙏🏿", + "🚾 🆒 🆓 🆕 🆖 🆗 🆙 🏧", + "0️⃣ 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣ 8️⃣ 9️⃣ 🔟", + "🇺🇸🇷🇺🇸 🇦🇫🇦🇲🇸", + "🇺🇸🇷🇺🇸🇦🇫🇦🇲", + "🇺🇸🇷🇺🇸🇦", + "123", + "١٢٣", + "ثم نفس سقطت وبالتحديد،, جزيرتي باستخدام أن دنو. إذ هنا؟ الستار وتنصيب كان. أهّل ايطاليا، بريطانيا-فرنسا قد أخذ. سليمان، إتفاقية بين ما, يذكر الحدود أي بعد, معاملة بولندا، الإطلاق عل إيو.", + "בְּרֵאשִׁית, בָּרָא אֱלֹהִים, אֵת הַשָּׁמַיִם, וְאֵת הָאָרֶץ", + "הָיְתָהtestالصفحات التّحول", + "﷽", + "ﷺ", + "مُنَاقَشَةُ سُبُلِ اِسْتِخْدَامِ اللُّغَةِ فِي النُّظُمِ الْقَائِمَةِ وَفِيم يَخُصَّ التَّطْبِيقَاتُ الْحاسُوبِيَّةُ، ", + "​", + " ", + "᠎", + " ", + "", + "␣", + "␢", + "␡", + "‪‪test‪", + "‫test‫", + "
test
", + "test⁠test‫", + "⁦test⁧", + "Ṱ̺̺̕o͞ ̷i̲̬͇̪͙n̝̗͕v̟̜̘̦͟o̶̙̰̠kè͚̮̺̪̹̱̤ ̖t̝͕̳̣̻̪͞h̼͓̲̦̳̘̲e͇̣̰̦̬͎ ̢̼̻̱̘h͚͎͙̜̣̲ͅi̦̲̣̰̤v̻͍e̺̭̳̪̰-m̢iͅn̖̺̞̲̯̰d̵̼̟͙̩̼̘̳ ̞̥̱̳̭r̛̗̘e͙p͠r̼̞̻̭̗e̺̠̣͟s̘͇̳͍̝͉e͉̥̯̞̲͚̬͜ǹ̬͎͎̟̖͇̤t͍̬̤͓̼̭͘ͅi̪̱n͠g̴͉ ͏͉ͅc̬̟h͡a̫̻̯͘o̫̟̖͍̙̝͉s̗̦̲.̨̹͈̣", + "̡͓̞ͅI̗̘̦͝n͇͇͙v̮̫ok̲̫̙͈i̖͙̭̹̠̞n̡̻̮̣̺g̲͈͙̭͙̬͎ ̰t͔̦h̞̲e̢̤ ͍̬̲͖f̴̘͕̣è͖ẹ̥̩l͖͔͚i͓͚̦͠n͖͍̗͓̳̮g͍ ̨o͚̪͡f̘̣̬ ̖̘͖̟͙̮c҉͔̫͖͓͇͖ͅh̵̤̣͚͔á̗̼͕ͅo̼̣̥s̱͈̺̖̦̻͢.̛̖̞̠̫̰", + "̗̺͖̹̯͓Ṯ̤͍̥͇͈h̲́e͏͓̼̗̙̼̣͔ ͇̜̱̠͓͍ͅN͕͠e̗̱z̘̝̜̺͙p̤̺̹͍̯͚e̠̻̠͜r̨̤͍̺̖͔̖̖d̠̟̭̬̝͟i̦͖̩͓͔̤a̠̗̬͉̙n͚͜ ̻̞̰͚ͅh̵͉i̳̞v̢͇ḙ͎͟-҉̭̩̼͔m̤̭̫i͕͇̝̦n̗͙ḍ̟ ̯̲͕͞ǫ̟̯̰̲͙̻̝f ̪̰̰̗̖̭̘͘c̦͍̲̞͍̩̙ḥ͚a̮͎̟̙͜ơ̩̹͎s̤.̝̝ ҉Z̡̖̜͖̰̣͉̜a͖̰͙̬͡l̲̫̳͍̩g̡̟̼̱͚̞̬ͅo̗͜.̟", + "̦H̬̤̗̤͝e͜ ̜̥̝̻͍̟́w̕h̖̯͓o̝͙̖͎̱̮ ҉̺̙̞̟͈W̷̼̭a̺̪͍į͈͕̭͙̯̜t̶̼̮s̘͙͖̕ ̠̫̠B̻͍͙͉̳ͅe̵h̵̬͇̫͙i̹͓̳̳̮͎̫̕n͟d̴̪̜̖ ̰͉̩͇͙̲͞ͅT͖̼͓̪͢h͏͓̮̻e̬̝̟ͅ ̤̹̝W͙̞̝͔͇͝ͅa͏͓͔̹̼̣l̴͔̰̤̟͔ḽ̫.͕", + "Z̮̞̠͙͔ͅḀ̗̞͈̻̗Ḷ͙͎̯̹̞͓G̻O̭̗̮", + "˙ɐnbᴉlɐ ɐuƃɐɯ ǝɹolop ʇǝ ǝɹoqɐl ʇn ʇunpᴉpᴉɔuᴉ ɹodɯǝʇ poɯsnᴉǝ op pǝs 'ʇᴉlǝ ƃuᴉɔsᴉdᴉpɐ ɹnʇǝʇɔǝsuoɔ 'ʇǝɯɐ ʇᴉs ɹolop ɯnsdᴉ ɯǝɹo˥", + "00˙Ɩ$-", + "The quick brown fox jumps over the lazy dog", + "𝐓𝐡𝐞 𝐪𝐮𝐢𝐜𝐤 𝐛𝐫𝐨𝐰𝐧 𝐟𝐨𝐱 𝐣𝐮𝐦𝐩𝐬 𝐨𝐯𝐞𝐫 𝐭𝐡𝐞 𝐥𝐚𝐳𝐲 𝐝𝐨𝐠", + "𝕿𝖍𝖊 𝖖𝖚𝖎𝖈𝖐 𝖇𝖗𝖔𝖜𝖓 𝖋𝖔𝖝 𝖏𝖚𝖒𝖕𝖘 𝖔𝖛𝖊𝖗 𝖙𝖍𝖊 𝖑𝖆𝖟𝖞 𝖉𝖔𝖌", + "𝑻𝒉𝒆 𝒒𝒖𝒊𝒄𝒌 𝒃𝒓𝒐𝒘𝒏 𝒇𝒐𝒙 𝒋𝒖𝒎𝒑𝒔 𝒐𝒗𝒆𝒓 𝒕𝒉𝒆 𝒍𝒂𝒛𝒚 𝒅𝒐𝒈", + "𝓣𝓱𝓮 𝓺𝓾𝓲𝓬𝓴 𝓫𝓻𝓸𝔀𝓷 𝓯𝓸𝔁 𝓳𝓾𝓶𝓹𝓼 𝓸𝓿𝓮𝓻 𝓽𝓱𝓮 𝓵𝓪𝔃𝔂 𝓭𝓸𝓰", + "𝕋𝕙𝕖 𝕢𝕦𝕚𝕔𝕜 𝕓𝕣𝕠𝕨𝕟 𝕗𝕠𝕩 𝕛𝕦𝕞𝕡𝕤 𝕠𝕧𝕖𝕣 𝕥𝕙𝕖 𝕝𝕒𝕫𝕪 𝕕𝕠𝕘", + "𝚃𝚑𝚎 𝚚𝚞𝚒𝚌𝚔 𝚋𝚛𝚘𝚠𝚗 𝚏𝚘𝚡 𝚓𝚞𝚖𝚙𝚜 𝚘𝚟𝚎𝚛 𝚝𝚑𝚎 𝚕𝚊𝚣𝚢 𝚍𝚘𝚐", + "⒯⒣⒠ ⒬⒰⒤⒞⒦ ⒝⒭⒪⒲⒩ ⒡⒪⒳ ⒥⒰⒨⒫⒮ ⒪⒱⒠⒭ ⒯⒣⒠ ⒧⒜⒵⒴ ⒟⒪⒢", + "", + "<script>alert('123');</script>", + "", + "", + "\">", + "'>", + ">", + "", + "< / script >< script >alert(123)< / script >", + " onfocus=JaVaSCript:alert(123) autofocus", + "\" onfocus=JaVaSCript:alert(123) autofocus", + "' onfocus=JaVaSCript:alert(123) autofocus", + "<script>alert(123)</script>", + "ript>alert(123)ript>", + "-->", + "\";alert(123);t=\"", + "';alert(123);t='", + "JavaSCript:alert(123)", + ";alert(123);", + "src=JaVaSCript:prompt(132)", + "\"><\\x3Cscript>javascript:alert(1)", + "'`\"><\\x00script>javascript:alert(1)", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "ABC
DEF", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "test", + "`\"'>", + "`\"'>", + "`\"'>", + "`\"'>", + "`\"'>", + "`\"'>", + "`\"'>", + "`\"'>", + "`\"'>", + "`\"'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "\"`'>", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "XXX", + "javascript:alert(1)\"` `>", + "", + "", + "<a href=http://foo.bar/#x=`y></a><img alt=\"`><img src=x:x onerror=javascript:alert(1)></a>\">", + "<!--[if]><script>javascript:alert(1)</script -->", + "<!--[if<img src=x onerror=javascript:alert(1)//]> -->", + "<script src=\"/\\%(jscript)s\"></script>", + "<script src=\"\\\\%(jscript)s\"></script>", + "<IMG \"\"\"><SCRIPT>alert(\"XSS\")</SCRIPT>\">", + "<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>", + "<IMG SRC=# onmouseover=\"alert('xxs')\">", + "<IMG SRC= onmouseover=\"alert('xxs')\">", + "<IMG onmouseover=\"alert('xxs')\">", + "<IMG SRC=javascript:alert('XSS')>", + "<IMG SRC=javascript:alert('XSS')>", + "<IMG SRC=javascript:alert('XSS')>", + "<IMG SRC=\"jav ascript:alert('XSS');\">", + "<IMG SRC=\"jav ascript:alert('XSS');\">", + "<IMG SRC=\"jav ascript:alert('XSS');\">", + "<IMG SRC=\"jav ascript:alert('XSS');\">", + "perl -e 'print \"<IMG SRC=java\\0script:alert(\\\"XSS\\\")>\";' > out", + "<IMG SRC=\"  javascript:alert('XSS');\">", + "<SCRIPT/XSS SRC=\"http://ha.ckers.org/xss.js\"></SCRIPT>", + "<BODY onload!#$%&()*~+-_.,:;?@[/|\\]^`=alert(\"XSS\")>", + "<SCRIPT/SRC=\"http://ha.ckers.org/xss.js\"></SCRIPT>", + "<<SCRIPT>alert(\"XSS\");//<</SCRIPT>", + "<SCRIPT SRC=http://ha.ckers.org/xss.js?< B >", + "<SCRIPT SRC=//ha.ckers.org/.j>", + "<IMG SRC=\"javascript:alert('XSS')\"", + "<iframe src=http://ha.ckers.org/scriptlet.html <", + "\\\";alert('XSS');//", + "<u oncopy=alert()> Copy me</u>", + "<i onwheel=alert(1)> Scroll over me </i>", + "<plaintext>", + "http://a/%%30%30", + "</textarea><script>alert(123)</script>", + "1;DROP TABLE users", + "1'; DROP TABLE users-- 1", + "' OR 1=1 -- 1", + "' OR '1'='1", + " ", + "%", + "_", + "-", + "--", + "--version", + "--help", + "$USER", + "/dev/null; touch /tmp/blns.fail ; echo", + "`touch /tmp/blns.fail`", + "$(touch /tmp/blns.fail)", + "@{[system \"touch /tmp/blns.fail\"]}", + "eval(\"puts 'hello world'\")", + "System(\"ls -al /\")", + "`ls -al /`", + "Kernel.exec(\"ls -al /\")", + "Kernel.exit(1)", + "%x('ls -al /')", + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><!DOCTYPE foo [ <!ELEMENT foo ANY ><!ENTITY xxe SYSTEM \"file:///etc/passwd\" >]><foo>&xxe;</foo>", + "$HOME", + "$ENV{'HOME'}", + "%d", + "%s", + "{0}", + "%*.*s", + "File:///", + "../../../../../../../../../../../etc/passwd%00", + "../../../../../../../../../../../etc/hosts", + "() { 0; }; touch /tmp/blns.shellshock1.fail;", + "() { _; } >_[$($())] { touch /tmp/blns.shellshock2.fail; }", + "<<< %s(un='%s') = %u", + "+++ATH0", + "CON", + "PRN", + "AUX", + "CLOCK$", + "NUL", + "A:", + "ZZ:", + "COM1", + "LPT1", + "LPT2", + "LPT3", + "COM2", + "COM3", + "COM4", + "DCC SEND STARTKEYLOGGER 0 0 0", + "Scunthorpe General Hospital", + "Penistone Community Church", + "Lightwater Country Park", + "Jimmy Clitheroe", + "Horniman Museum", + "shitake mushrooms", + "RomansInSussex.co.uk", + "http://www.cum.qc.ca/", + "Craig Cockburn, Software Specialist", + "Linda Callahan", + "Dr. Herman I. Libshitz", + "magna cum laude", + "Super Bowl XXX", + "medieval erection of parapets", + "evaluate", + "mocha", + "expression", + "Arsenal canal", + "classic", + "Tyson Gay", + "Dick Van Dyke", + "basement", + "If you're reading this, you've been in a coma for almost 20 years now. We're trying a new technique. We don't know where this message will end up in your dream, but we hope it works. Please wake up, we miss you.", + "Roses are \u001b[0;31mred\u001b[0m, violets are \u001b[0;34mblue. Hope you enjoy terminal hue", + "But now...\u001b[20Cfor my greatest trick...\u001b[8m", + "The quic\b\b\b\b\b\bk brown fo\u0007\u0007\u0007\u0007\u0007\u0007\u0007\u0007\u0007\u0007\u0007x... [Beeeep]", + "Powerلُلُصّبُلُلصّبُررً ॣ ॣh ॣ ॣ冗" +] diff --git a/json_serializable-3.5.2/test/literal/json_literal.dart b/json_serializable-3.5.2/test/literal/json_literal.dart new file mode 100644 index 000000000..b7bc2a0bb --- /dev/null +++ b/json_serializable-3.5.2/test/literal/json_literal.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2017, 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. + +import 'package:json_annotation/json_annotation.dart'; +part 'json_literal.g.dart'; + +@JsonLiteral('json_literal.json') +List get data => _$dataJsonLiteral; + +@JsonLiteral('json_literal.json', asConst: true) +List get asConst => _$asConstJsonLiteral; + +/// From https://github.com/minimaxir/big-list-of-naughty-strings +/// blns.json @ 96f50492b278aeb2bfa40c4acbdbf6311312bf30 +@JsonLiteral('big-list-of-naughty-strings.json', asConst: true) +List get naughtyStrings => _$naughtyStringsJsonLiteral; diff --git a/json_serializable-3.5.2/test/literal/json_literal.g.dart b/json_serializable-3.5.2/test/literal/json_literal.g.dart new file mode 100644 index 000000000..5ffcbe848 --- /dev/null +++ b/json_serializable-3.5.2/test/literal/json_literal.g.dart @@ -0,0 +1,603 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'json_literal.dart'; + +// ************************************************************************** +// JsonLiteralGenerator +// ************************************************************************** + +final _$dataJsonLiteral = [ + { + 'backspace': '\b', + 'tab': '\t', + 'new line': '\n', + 'vertical tab': '\v', + 'form feed': '\r', + 'carriage return': '\r', + 'delete': '\x7F' + }, + 'simple string', + "'string with single quotes'", + '"string with double quotes"', + '\'With singles and \"doubles\"\'', + r'dollar $igns', + r"'single quotes and dollor $ig$'", + r"${'nice!'}", + '""hello""', + r'""$double quotes and dollar signs""', + '\$scary with \'single quotes\' and triple-doubles \"\"\"oh no!', + 'Dollar signs: \$ vs \\\$ vs \\\\\$', + 'Slashes \\nice slash\\', + 'slashes \\ and dollars \$ with white \n space', + "'''triple quoted strings should be\nfine!'''", + '"""as with triple-double-quotes"""', + '\"\"\"as with triple-double-quotes even when \'mixed\'\"\"\"', + null, + true, + false, + 5, + 5.5351, + -5.5, + {}, + { + 'null': null, + 'int': 42, + 'double': 42.0, + 'string': 'string', + 'list': [], + 'bool': true + } +]; + +const _$asConstJsonLiteral = [ + { + 'backspace': '\b', + 'tab': '\t', + 'new line': '\n', + 'vertical tab': '\v', + 'form feed': '\r', + 'carriage return': '\r', + 'delete': '\x7F' + }, + 'simple string', + "'string with single quotes'", + '"string with double quotes"', + '\'With singles and \"doubles\"\'', + r'dollar $igns', + r"'single quotes and dollor $ig$'", + r"${'nice!'}", + '""hello""', + r'""$double quotes and dollar signs""', + '\$scary with \'single quotes\' and triple-doubles \"\"\"oh no!', + 'Dollar signs: \$ vs \\\$ vs \\\\\$', + 'Slashes \\nice slash\\', + 'slashes \\ and dollars \$ with white \n space', + "'''triple quoted strings should be\nfine!'''", + '"""as with triple-double-quotes"""', + '\"\"\"as with triple-double-quotes even when \'mixed\'\"\"\"', + null, + true, + false, + 5, + 5.5351, + -5.5, + {}, + { + 'null': null, + 'int': 42, + 'double': 42.0, + 'string': 'string', + 'list': [], + 'bool': true + } +]; + +const _$naughtyStringsJsonLiteral = [ + '', + 'undefined', + 'undef', + 'null', + 'NULL', + '(null)', + 'nil', + 'NIL', + 'true', + 'false', + 'True', + 'False', + 'TRUE', + 'FALSE', + 'None', + 'hasOwnProperty', + '\\', + '\\\\', + '0', + '1', + '1.00', + r'$1.00', + '1/2', + '1E2', + '1E02', + '1E+02', + '-1', + '-1.00', + r'-$1.00', + '-1/2', + '-1E2', + '-1E02', + '-1E+02', + '1/0', + '0/0', + '-2147483648/-1', + '-9223372036854775808/-1', + '-0', + '-0.0', + '+0', + '+0.0', + '0.00', + '0..0', + '.', + '0.0.0', + '0,00', + '0,,0', + ',', + '0,0,0', + '0.0/0', + '1.0/0.0', + '0.0/0.0', + '1,0/0,0', + '0,0/0,0', + '--1', + '-', + '-.', + '-,', + '999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999', + 'NaN', + 'Infinity', + '-Infinity', + 'INF', + '1#INF', + '-1#IND', + '1#QNAN', + '1#SNAN', + '1#IND', + '0x0', + '0xffffffff', + '0xffffffffffffffff', + '0xabad1dea', + '123456789012345678901234567890123456789', + '1,000.00', + '1 000.00', + "1'000.00", + '1,000,000.00', + '1 000 000.00', + "1'000'000.00", + '1.000,00', + '1 000,00', + "1'000,00", + '1.000.000,00', + '1 000 000,00', + "1'000'000,00", + '01000', + '08', + '09', + '2.2250738585072011e-308', + ",./;'[]\\-=", + '<>?:"{}|_+', + r'!@#$%^&*()`~', + '\x01\x02\x03\x04\x05\x06\x07\b\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x7F', + '€‚ƒ„†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ', + '\t\v\f …             ​

   ', + '­؀؁؂؃؄؅؜۝܏᠎​‌‍‎‏‪‫‬‭‮⁠⁡⁢⁣⁤⁦⁧⁨⁩𑂽𛲠𛲡𛲢𛲣𝅳𝅴𝅵𝅶𝅷𝅸𝅹𝅺󠀁󠀠󠀡󠀢󠀣󠀤󠀥󠀦󠀧󠀨󠀩󠀪󠀫󠀬󠀭󠀮󠀯󠀰󠀱󠀲󠀳󠀴󠀵󠀶󠀷󠀸󠀹󠀺󠀻󠀼󠀽󠀾󠀿󠁀󠁁󠁂󠁃󠁄󠁅󠁆󠁇󠁈󠁉󠁊󠁋󠁌󠁍󠁎󠁏󠁐󠁑󠁒󠁓󠁔󠁕󠁖󠁗󠁘󠁙󠁚󠁛󠁜󠁝󠁞󠁟󠁠󠁡󠁢󠁣󠁤󠁥󠁦󠁧󠁨󠁩󠁪󠁫󠁬󠁭󠁮󠁯󠁰󠁱󠁲󠁳󠁴󠁵󠁶󠁷󠁸󠁹󠁺󠁻󠁼󠁽󠁾󠁿', + '', + '￾', + 'Ω≈ç√∫˜µ≤≥÷', + 'åß∂ƒ©˙∆˚¬…æ', + 'œ∑´®†¥¨ˆøπ“‘', + '¡™£¢∞§¶•ªº–≠', + '¸˛Ç◊ı˜Â¯˘¿', + 'ÅÍÎÏ˝ÓÔÒÚÆ☃', + 'Œ„´‰ˇÁ¨ˆØ∏”’', + '`⁄€‹›fifl‡°·‚—±', + '⅛⅜⅝⅞', + 'ЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя', + '٠١٢٣٤٥٦٧٨٩', + '⁰⁴⁵', + '₀₁₂', + '⁰⁴⁵₀₁₂', + 'ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็ ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็ ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็', + "'", + '"', + "''", + '""', + '\'\"\'', + '\"\'\'\'\'\"\'\"', + '\"\'\"\'\"\'\'\'\'\"', + '<foo val=“bar” />', + '<foo val=“bar” />', + '<foo val=”bar“ />', + "<foo val=`bar' />", + '田中さんにあげて下さい', + 'パーティーへ行かないか', + '和製漢語', + '部落格', + '사회과학원 어학연구소', + '찦차를 타고 온 펲시맨과 쑛다리 똠방각하', + '社會科學院語學研究所', + '울란바토르', + '𠜎𠜱𠝹𠱓𠱸𠲖𠳏', + 'Ⱥ', + 'Ⱦ', + 'ヽ༼ຈل͜ຈ༽ノ ヽ༼ຈل͜ຈ༽ノ ', + '(。◕ ∀ ◕。)', + '`ィ(´∀`∩', + '__ロ(,_,*)', + '・( ̄∀ ̄)・:*:', + '゚・✿ヾ╲(。◕‿◕。)╱✿・゚', + ',。・:*:・゜’( ☻ ω ☻ )。・:*:・゜’', + '(╯°□°)╯︵ ┻━┻)', + '(ノಥ益ಥ)ノ ┻━┻', + '┬─┬ノ( º _ ºノ)', + '( ͡° ͜ʖ ͡°)', + '😍', + '👩🏽', + '👾 🙇 💁 🙅 🙆 🙋 🙎 🙍', + '🐵 🙈 🙉 🙊', + '❤️ 💔 💌 💕 💞 💓 💗 💖 💘 💝 💟 💜 💛 💚 💙', + '✋🏿 💪🏿 👐🏿 🙌🏿 👏🏿 🙏🏿', + '🚾 🆒 🆓 🆕 🆖 🆗 🆙 🏧', + '0️⃣ 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣ 8️⃣ 9️⃣ 🔟', + '🇺🇸🇷🇺🇸 🇦🇫🇦🇲🇸', + '🇺🇸🇷🇺🇸🇦🇫🇦🇲', + '🇺🇸🇷🇺🇸🇦', + '123', + '١٢٣', + 'ثم نفس سقطت وبالتحديد،, جزيرتي باستخدام أن دنو. إذ هنا؟ الستار وتنصيب كان. أهّل ايطاليا، بريطانيا-فرنسا قد أخذ. سليمان، إتفاقية بين ما, يذكر الحدود أي بعد, معاملة بولندا، الإطلاق عل إيو.', + 'בְּרֵאשִׁית, בָּרָא אֱלֹהִים, אֵת הַשָּׁמַיִם, וְאֵת הָאָרֶץ', + 'הָיְתָהtestالصفحات التّحول', + '﷽', + 'ﷺ', + 'مُنَاقَشَةُ سُبُلِ اِسْتِخْدَامِ اللُّغَةِ فِي النُّظُمِ الْقَائِمَةِ وَفِيم يَخُصَّ التَّطْبِيقَاتُ الْحاسُوبِيَّةُ، ', + '​', + ' ', + '᠎', + ' ', + '', + '␣', + '␢', + '␡', + '‪‪test‪', + '‫test‫', + '
test
', + 'test⁠test‫', + '⁦test⁧', + 'Ṱ̺̺̕o͞ ̷i̲̬͇̪͙n̝̗͕v̟̜̘̦͟o̶̙̰̠kè͚̮̺̪̹̱̤ ̖t̝͕̳̣̻̪͞h̼͓̲̦̳̘̲e͇̣̰̦̬͎ ̢̼̻̱̘h͚͎͙̜̣̲ͅi̦̲̣̰̤v̻͍e̺̭̳̪̰-m̢iͅn̖̺̞̲̯̰d̵̼̟͙̩̼̘̳ ̞̥̱̳̭r̛̗̘e͙p͠r̼̞̻̭̗e̺̠̣͟s̘͇̳͍̝͉e͉̥̯̞̲͚̬͜ǹ̬͎͎̟̖͇̤t͍̬̤͓̼̭͘ͅi̪̱n͠g̴͉ ͏͉ͅc̬̟h͡a̫̻̯͘o̫̟̖͍̙̝͉s̗̦̲.̨̹͈̣', + '̡͓̞ͅI̗̘̦͝n͇͇͙v̮̫ok̲̫̙͈i̖͙̭̹̠̞n̡̻̮̣̺g̲͈͙̭͙̬͎ ̰t͔̦h̞̲e̢̤ ͍̬̲͖f̴̘͕̣è͖ẹ̥̩l͖͔͚i͓͚̦͠n͖͍̗͓̳̮g͍ ̨o͚̪͡f̘̣̬ ̖̘͖̟͙̮c҉͔̫͖͓͇͖ͅh̵̤̣͚͔á̗̼͕ͅo̼̣̥s̱͈̺̖̦̻͢.̛̖̞̠̫̰', + '̗̺͖̹̯͓Ṯ̤͍̥͇͈h̲́e͏͓̼̗̙̼̣͔ ͇̜̱̠͓͍ͅN͕͠e̗̱z̘̝̜̺͙p̤̺̹͍̯͚e̠̻̠͜r̨̤͍̺̖͔̖̖d̠̟̭̬̝͟i̦͖̩͓͔̤a̠̗̬͉̙n͚͜ ̻̞̰͚ͅh̵͉i̳̞v̢͇ḙ͎͟-҉̭̩̼͔m̤̭̫i͕͇̝̦n̗͙ḍ̟ ̯̲͕͞ǫ̟̯̰̲͙̻̝f ̪̰̰̗̖̭̘͘c̦͍̲̞͍̩̙ḥ͚a̮͎̟̙͜ơ̩̹͎s̤.̝̝ ҉Z̡̖̜͖̰̣͉̜a͖̰͙̬͡l̲̫̳͍̩g̡̟̼̱͚̞̬ͅo̗͜.̟', + '̦H̬̤̗̤͝e͜ ̜̥̝̻͍̟́w̕h̖̯͓o̝͙̖͎̱̮ ҉̺̙̞̟͈W̷̼̭a̺̪͍į͈͕̭͙̯̜t̶̼̮s̘͙͖̕ ̠̫̠B̻͍͙͉̳ͅe̵h̵̬͇̫͙i̹͓̳̳̮͎̫̕n͟d̴̪̜̖ ̰͉̩͇͙̲͞ͅT͖̼͓̪͢h͏͓̮̻e̬̝̟ͅ ̤̹̝W͙̞̝͔͇͝ͅa͏͓͔̹̼̣l̴͔̰̤̟͔ḽ̫.͕', + 'Z̮̞̠͙͔ͅḀ̗̞͈̻̗Ḷ͙͎̯̹̞͓G̻O̭̗̮', + "˙ɐnbᴉlɐ ɐuƃɐɯ ǝɹolop ʇǝ ǝɹoqɐl ʇn ʇunpᴉpᴉɔuᴉ ɹodɯǝʇ poɯsnᴉǝ op pǝs 'ʇᴉlǝ ƃuᴉɔsᴉdᴉpɐ ɹnʇǝʇɔǝsuoɔ 'ʇǝɯɐ ʇᴉs ɹolop ɯnsdᴉ ɯǝɹo˥", + r'00˙Ɩ$-', + 'The quick brown fox jumps over the lazy dog', + '𝐓𝐡𝐞 𝐪𝐮𝐢𝐜𝐤 𝐛𝐫𝐨𝐰𝐧 𝐟𝐨𝐱 𝐣𝐮𝐦𝐩𝐬 𝐨𝐯𝐞𝐫 𝐭𝐡𝐞 𝐥𝐚𝐳𝐲 𝐝𝐨𝐠', + '𝕿𝖍𝖊 𝖖𝖚𝖎𝖈𝖐 𝖇𝖗𝖔𝖜𝖓 𝖋𝖔𝖝 𝖏𝖚𝖒𝖕𝖘 𝖔𝖛𝖊𝖗 𝖙𝖍𝖊 𝖑𝖆𝖟𝖞 𝖉𝖔𝖌', + '𝑻𝒉𝒆 𝒒𝒖𝒊𝒄𝒌 𝒃𝒓𝒐𝒘𝒏 𝒇𝒐𝒙 𝒋𝒖𝒎𝒑𝒔 𝒐𝒗𝒆𝒓 𝒕𝒉𝒆 𝒍𝒂𝒛𝒚 𝒅𝒐𝒈', + '𝓣𝓱𝓮 𝓺𝓾𝓲𝓬𝓴 𝓫𝓻𝓸𝔀𝓷 𝓯𝓸𝔁 𝓳𝓾𝓶𝓹𝓼 𝓸𝓿𝓮𝓻 𝓽𝓱𝓮 𝓵𝓪𝔃𝔂 𝓭𝓸𝓰', + '𝕋𝕙𝕖 𝕢𝕦𝕚𝕔𝕜 𝕓𝕣𝕠𝕨𝕟 𝕗𝕠𝕩 𝕛𝕦𝕞𝕡𝕤 𝕠𝕧𝕖𝕣 𝕥𝕙𝕖 𝕝𝕒𝕫𝕪 𝕕𝕠𝕘', + '𝚃𝚑𝚎 𝚚𝚞𝚒𝚌𝚔 𝚋𝚛𝚘𝚠𝚗 𝚏𝚘𝚡 𝚓𝚞𝚖𝚙𝚜 𝚘𝚟𝚎𝚛 𝚝𝚑𝚎 𝚕𝚊𝚣𝚢 𝚍𝚘𝚐', + '⒯⒣⒠ ⒬⒰⒤⒞⒦ ⒝⒭⒪⒲⒩ ⒡⒪⒳ ⒥⒰⒨⒫⒮ ⒪⒱⒠⒭ ⒯⒣⒠ ⒧⒜⒵⒴ ⒟⒪⒢', + '<script>alert(123)</script>', + '<script>alert('123');</script>', + '<img src=x onerror=alert(123) />', + '<svg><script>123<1>alert(123)</script>', + '"><script>alert(123)</script>', + "'><script>alert(123)</script>", + '><script>alert(123)</script>', + '</script><script>alert(123)</script>', + '< / script >< script >alert(123)< / script >', + ' onfocus=JaVaSCript:alert(123) autofocus', + '" onfocus=JaVaSCript:alert(123) autofocus', + "' onfocus=JaVaSCript:alert(123) autofocus", + '<script>alert(123)</script>', + '<sc<script>ript>alert(123)</sc</script>ript>', + '--><script>alert(123)</script>', + '";alert(123);t="', + "';alert(123);t='", + 'JavaSCript:alert(123)', + ';alert(123);', + 'src=JaVaSCript:prompt(132)', + '"><script>alert(123);</script x="', + "'><script>alert(123);</script x='", + '><script>alert(123);</script x=', + '" autofocus onkeyup="javascript:alert(123)', + "' autofocus onkeyup='javascript:alert(123)", + '<script\\x20type="text/javascript">javascript:alert(1);</script>', + '<script\\x3Etype="text/javascript">javascript:alert(1);</script>', + '<script\\x0Dtype="text/javascript">javascript:alert(1);</script>', + '<script\\x09type="text/javascript">javascript:alert(1);</script>', + '<script\\x0Ctype="text/javascript">javascript:alert(1);</script>', + '<script\\x2Ftype="text/javascript">javascript:alert(1);</script>', + '<script\\x0Atype="text/javascript">javascript:alert(1);</script>', + '\'`\"><\\x3Cscript>javascript:alert(1)</script>', + '\'`\"><\\x00script>javascript:alert(1)</script>', + 'ABC<div style="x\\x3Aexpression(javascript:alert(1)">DEF', + 'ABC<div style="x:expression\\x5C(javascript:alert(1)">DEF', + 'ABC<div style="x:expression\\x00(javascript:alert(1)">DEF', + 'ABC<div style="x:exp\\x00ression(javascript:alert(1)">DEF', + 'ABC<div style="x:exp\\x5Cression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\x0Aexpression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\x09expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE3\\x80\\x80expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE2\\x80\\x84expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xC2\\xA0expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE2\\x80\\x80expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE2\\x80\\x8Aexpression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\x0Dexpression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\x0Cexpression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE2\\x80\\x87expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xEF\\xBB\\xBFexpression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\x20expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE2\\x80\\x88expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\x00expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE2\\x80\\x8Bexpression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE2\\x80\\x86expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE2\\x80\\x85expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE2\\x80\\x82expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\x0Bexpression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE2\\x80\\x81expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE2\\x80\\x83expression(javascript:alert(1)">DEF', + 'ABC<div style="x:\\xE2\\x80\\x89expression(javascript:alert(1)">DEF', + '<a href="\\x0Bjavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x0Fjavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xC2\\xA0javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x05javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE1\\xA0\\x8Ejavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x18javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x11javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\x88javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\x89javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\x80javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x17javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x03javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x0Ejavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x1Ajavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x00javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x10javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\x82javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x20javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x13javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x09javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\x8Ajavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x14javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x19javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\xAFjavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x1Fjavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\x81javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x1Djavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\x87javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x07javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE1\\x9A\\x80javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\x83javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x04javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x01javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x08javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\x84javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\x86javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE3\\x80\\x80javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x12javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x0Djavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x0Ajavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x0Cjavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x15javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\xA8javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x16javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x02javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x1Bjavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x06javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\xA9javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x80\\x85javascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x1Ejavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\xE2\\x81\\x9Fjavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="\\x1Cjavascript:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="javascript\\x00:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="javascript\\x3A:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="javascript\\x09:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="javascript\\x0D:javascript:alert(1)" id="fuzzelement1">test</a>', + '<a href="javascript\\x0A:javascript:alert(1)" id="fuzzelement1">test</a>', + '`\"\'><img src=xxx:x \\x0Aonerror=javascript:alert(1)>', + '`\"\'><img src=xxx:x \\x22onerror=javascript:alert(1)>', + '`\"\'><img src=xxx:x \\x0Bonerror=javascript:alert(1)>', + '`\"\'><img src=xxx:x \\x0Donerror=javascript:alert(1)>', + '`\"\'><img src=xxx:x \\x2Fonerror=javascript:alert(1)>', + '`\"\'><img src=xxx:x \\x09onerror=javascript:alert(1)>', + '`\"\'><img src=xxx:x \\x0Conerror=javascript:alert(1)>', + '`\"\'><img src=xxx:x \\x00onerror=javascript:alert(1)>', + '`\"\'><img src=xxx:x \\x27onerror=javascript:alert(1)>', + '`\"\'><img src=xxx:x \\x20onerror=javascript:alert(1)>', + '\"`\'><script>\\x3Bjavascript:alert(1)</script>', + '\"`\'><script>\\x0Djavascript:alert(1)</script>', + '\"`\'><script>\\xEF\\xBB\\xBFjavascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\x81javascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\x84javascript:alert(1)</script>', + '\"`\'><script>\\xE3\\x80\\x80javascript:alert(1)</script>', + '\"`\'><script>\\x09javascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\x89javascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\x85javascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\x88javascript:alert(1)</script>', + '\"`\'><script>\\x00javascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\xA8javascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\x8Ajavascript:alert(1)</script>', + '\"`\'><script>\\xE1\\x9A\\x80javascript:alert(1)</script>', + '\"`\'><script>\\x0Cjavascript:alert(1)</script>', + '\"`\'><script>\\x2Bjavascript:alert(1)</script>', + '\"`\'><script>\\xF0\\x90\\x96\\x9Ajavascript:alert(1)</script>', + '\"`\'><script>-javascript:alert(1)</script>', + '\"`\'><script>\\x0Ajavascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\xAFjavascript:alert(1)</script>', + '\"`\'><script>\\x7Ejavascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\x87javascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x81\\x9Fjavascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\xA9javascript:alert(1)</script>', + '\"`\'><script>\\xC2\\x85javascript:alert(1)</script>', + '\"`\'><script>\\xEF\\xBF\\xAEjavascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\x83javascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\x8Bjavascript:alert(1)</script>', + '\"`\'><script>\\xEF\\xBF\\xBEjavascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\x80javascript:alert(1)</script>', + '\"`\'><script>\\x21javascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\x82javascript:alert(1)</script>', + '\"`\'><script>\\xE2\\x80\\x86javascript:alert(1)</script>', + '\"`\'><script>\\xE1\\xA0\\x8Ejavascript:alert(1)</script>', + '\"`\'><script>\\x0Bjavascript:alert(1)</script>', + '\"`\'><script>\\x20javascript:alert(1)</script>', + '\"`\'><script>\\xC2\\xA0javascript:alert(1)</script>', + '<img \\x00src=x onerror="alert(1)">', + '<img \\x47src=x onerror="javascript:alert(1)">', + '<img \\x11src=x onerror="javascript:alert(1)">', + '<img \\x12src=x onerror="javascript:alert(1)">', + '<img\\x47src=x onerror="javascript:alert(1)">', + '<img\\x10src=x onerror="javascript:alert(1)">', + '<img\\x13src=x onerror="javascript:alert(1)">', + '<img\\x32src=x onerror="javascript:alert(1)">', + '<img\\x47src=x onerror="javascript:alert(1)">', + '<img\\x11src=x onerror="javascript:alert(1)">', + '<img \\x47src=x onerror="javascript:alert(1)">', + '<img \\x34src=x onerror="javascript:alert(1)">', + '<img \\x39src=x onerror="javascript:alert(1)">', + '<img \\x00src=x onerror="javascript:alert(1)">', + '<img src\\x09=x onerror="javascript:alert(1)">', + '<img src\\x10=x onerror="javascript:alert(1)">', + '<img src\\x13=x onerror="javascript:alert(1)">', + '<img src\\x32=x onerror="javascript:alert(1)">', + '<img src\\x12=x onerror="javascript:alert(1)">', + '<img src\\x11=x onerror="javascript:alert(1)">', + '<img src\\x00=x onerror="javascript:alert(1)">', + '<img src\\x47=x onerror="javascript:alert(1)">', + '<img src=x\\x09onerror="javascript:alert(1)">', + '<img src=x\\x10onerror="javascript:alert(1)">', + '<img src=x\\x11onerror="javascript:alert(1)">', + '<img src=x\\x12onerror="javascript:alert(1)">', + '<img src=x\\x13onerror="javascript:alert(1)">', + '<img[a][b][c]src[d]=x[e]onerror=[f]"alert(1)">', + '<img src=x onerror=\\x09"javascript:alert(1)">', + '<img src=x onerror=\\x10"javascript:alert(1)">', + '<img src=x onerror=\\x11"javascript:alert(1)">', + '<img src=x onerror=\\x12"javascript:alert(1)">', + '<img src=x onerror=\\x32"javascript:alert(1)">', + '<img src=x onerror=\\x00"javascript:alert(1)">', + '<a href=java script:javascript:alert(1)>XXX</a>', + '<img src="x` `<script>javascript:alert(1)</script>"` `>', + '<img src onerror /\" \'\"= alt=javascript:alert(1)//\">', + '<title onpropertychange=javascript:alert(1)>', + '<a href=http://foo.bar/#x=`y></a><img alt="`><img src=x:x onerror=javascript:alert(1)></a>">', + '<!--[if]><script>javascript:alert(1)</script -->', + '<!--[if<img src=x onerror=javascript:alert(1)//]> -->', + '<script src="/\\%(jscript)s"></script>', + '<script src="\\\\%(jscript)s"></script>', + '<IMG """><SCRIPT>alert("XSS")</SCRIPT>">', + '<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>', + '<IMG SRC=# onmouseover=\"alert(\'xxs\')\">', + '<IMG SRC= onmouseover=\"alert(\'xxs\')\">', + '<IMG onmouseover=\"alert(\'xxs\')\">', + '<IMG SRC=javascript:alert('XSS')>', + '<IMG SRC=javascript:alert('XSS')>', + '<IMG SRC=javascript:alert('XSS')>', + '<IMG SRC=\"jav ascript:alert(\'XSS\');\">', + '<IMG SRC=\"jav ascript:alert(\'XSS\');\">', + '<IMG SRC=\"jav ascript:alert(\'XSS\');\">', + '<IMG SRC=\"jav ascript:alert(\'XSS\');\">', + 'perl -e \'print \"<IMG SRC=java\\0script:alert(\\\"XSS\\\")>\";\' > out', + '<IMG SRC=\"  javascript:alert(\'XSS\');\">', + '<SCRIPT/XSS SRC="http://ha.ckers.org/xss.js"></SCRIPT>', + '<BODY onload!#\$%&()*~+-_.,:;?@[/|\\]^`=alert(\"XSS\")>', + '<SCRIPT/SRC="http://ha.ckers.org/xss.js"></SCRIPT>', + '<<SCRIPT>alert("XSS");//<</SCRIPT>', + '<SCRIPT SRC=http://ha.ckers.org/xss.js?< B >', + '<SCRIPT SRC=//ha.ckers.org/.j>', + '<IMG SRC=\"javascript:alert(\'XSS\')\"', + '<iframe src=http://ha.ckers.org/scriptlet.html <', + '\\\";alert(\'XSS\');//', + '<u oncopy=alert()> Copy me</u>', + '<i onwheel=alert(1)> Scroll over me </i>', + '<plaintext>', + 'http://a/%%30%30', + '</textarea><script>alert(123)</script>', + '1;DROP TABLE users', + "1'; DROP TABLE users-- 1", + "' OR 1=1 -- 1", + "' OR '1'='1", + ' ', + '%', + '_', + '-', + '--', + '--version', + '--help', + r'$USER', + '/dev/null; touch /tmp/blns.fail ; echo', + '`touch /tmp/blns.fail`', + r'$(touch /tmp/blns.fail)', + '@{[system "touch /tmp/blns.fail"]}', + 'eval(\"puts \'hello world\'\")', + 'System("ls -al /")', + '`ls -al /`', + 'Kernel.exec("ls -al /")', + 'Kernel.exit(1)', + "%x('ls -al /')", + '<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE foo [ <!ELEMENT foo ANY ><!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo>', + r'$HOME', + r"$ENV{'HOME'}", + '%d', + '%s', + '{0}', + '%*.*s', + 'File:///', + '../../../../../../../../../../../etc/passwd%00', + '../../../../../../../../../../../etc/hosts', + '() { 0; }; touch /tmp/blns.shellshock1.fail;', + r'() { _; } >_[$($())] { touch /tmp/blns.shellshock2.fail; }', + "<<< %s(un='%s') = %u", + '+++ATH0', + 'CON', + 'PRN', + 'AUX', + r'CLOCK$', + 'NUL', + 'A:', + 'ZZ:', + 'COM1', + 'LPT1', + 'LPT2', + 'LPT3', + 'COM2', + 'COM3', + 'COM4', + 'DCC SEND STARTKEYLOGGER 0 0 0', + 'Scunthorpe General Hospital', + 'Penistone Community Church', + 'Lightwater Country Park', + 'Jimmy Clitheroe', + 'Horniman Museum', + 'shitake mushrooms', + 'RomansInSussex.co.uk', + 'http://www.cum.qc.ca/', + 'Craig Cockburn, Software Specialist', + 'Linda Callahan', + 'Dr. Herman I. Libshitz', + 'magna cum laude', + 'Super Bowl XXX', + 'medieval erection of parapets', + 'evaluate', + 'mocha', + 'expression', + 'Arsenal canal', + 'classic', + 'Tyson Gay', + 'Dick Van Dyke', + 'basement', + "If you're reading this, you've been in a coma for almost 20 years now. We're trying a new technique. We don't know where this message will end up in your dream, but we hope it works. Please wake up, we miss you.", + 'Roses are \x1B[0;31mred\x1B[0m, violets are \x1B[0;34mblue. Hope you enjoy terminal hue', + 'But now...\x1B[20Cfor my greatest trick...\x1B[8m', + 'The quic\b\b\b\b\b\bk brown fo\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07x... [Beeeep]', + 'Powerلُلُصّبُلُلصّبُررً ॣ ॣh ॣ ॣ冗' +]; diff --git a/json_serializable-3.5.2/test/literal/json_literal.json b/json_serializable-3.5.2/test/literal/json_literal.json new file mode 100644 index 000000000..1f5515877 --- /dev/null +++ b/json_serializable-3.5.2/test/literal/json_literal.json @@ -0,0 +1,42 @@ +[ + { + "backspace": "\b", + "tab": "\t", + "new line": "\n", + "vertical tab": "\u000b", + "form feed": "\r", + "carriage return": "\r", + "delete": "\u007F" + }, + "simple string", + "'string with single quotes'", + "\"string with double quotes\"", + "'With singles and \"doubles\"'", + "dollar $igns", + "'single quotes and dollor $ig$'", + "${'nice!'}", + "\"\"hello\"\"", + "\"\"$double quotes and dollar signs\"\"", + "$scary with 'single quotes' and triple-doubles \"\"\"oh no!", + "Dollar signs: $ vs \\$ vs \\\\$", + "Slashes \\nice slash\\", + "slashes \\ and dollars $ with white \n space", + "'''triple quoted strings should be\nfine!'''", + "\"\"\"as with triple-double-quotes\"\"\"", + "\"\"\"as with triple-double-quotes even when 'mixed'\"\"\"", + null, + true, + false, + 5, + 5.5351, + -5.5, + {}, + { + "null": null, + "int": 42, + "double": 42.0, + "string": "string", + "list": [], + "bool": true + } +] \ No newline at end of file diff --git a/json_serializable-3.5.2/test/literal/json_literal_test.dart b/json_serializable-3.5.2/test/literal/json_literal_test.dart new file mode 100644 index 000000000..d8d6c2643 --- /dev/null +++ b/json_serializable-3.5.2/test/literal/json_literal_test.dart @@ -0,0 +1,39 @@ +// 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. + +@TestOn('vm') +import 'dart:convert'; +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'json_literal.dart'; + +void main() { + test('literal round-trip', () { + final dataFilePath = p.join('test', 'literal', 'json_literal.json'); + final dataFile = File(dataFilePath); + + final dataString = loudEncode(json.decode(dataFile.readAsStringSync())); + // FYI: nice to re-write the test data when it's changed to keep it pretty + // ... but not a good idea to ship this + // dataFile.writeAsStringSync(dataString.replaceAll('\u007F', '\\u007F')); + final dartString = loudEncode(data); + + expect(dartString, dataString); + }); + + test('naughty strings', () { + final dataFilePath = + p.join('test', 'literal', 'big-list-of-naughty-strings.json'); + final dataFile = File(dataFilePath); + + final dataString = loudEncode(json.decode(dataFile.readAsStringSync())); + final dartString = loudEncode(naughtyStrings); + + expect(dartString, dataString); + }); +} diff --git a/json_serializable-3.5.2/test/readme_test.dart b/json_serializable-3.5.2/test/readme_test.dart new file mode 100644 index 000000000..c11c50a98 --- /dev/null +++ b/json_serializable-3.5.2/test/readme_test.dart @@ -0,0 +1,63 @@ +// 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. + +@TestOn('vm') +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +void main() { + String readmeContent; + + setUpAll(() { + readmeContent = File('README.md').readAsStringSync(); + }); + + test('example.dart', () { + final exampleContent = _getExampleContent('example.dart'); + expect(readmeContent, contains(exampleContent)); + }); + + test('example.g.dart', () { + final exampleGeneratedContent = _getExampleContent('example.g.dart'); + expect(readmeContent, contains(exampleGeneratedContent)); + }); + + test('doc/doc.md', () { + final docContent = File(p.join('doc', 'doc.md')).readAsStringSync(); + expect(readmeContent, contains(docContent)); + }); +} + +String _getExampleContent(String fileName) { + final lines = File(p.join('example', fileName)).readAsLinesSync(); + + var lastHadContent = false; + + // All lines with content, except those starting with `/`. + // Also exclude blank lines that follow other blank lines + final cleanedSource = lines.where((l) { + if (l.startsWith(r'/')) { + return false; + } + + if (l.trim().isNotEmpty) { + lastHadContent = true; + return true; + } + + if (lastHadContent) { + lastHadContent = false; + return true; + } + + return false; + }).join('\n'); + + return ''' +```dart +$cleanedSource +```'''; +} diff --git a/json_serializable-3.5.2/test/shared_config.dart b/json_serializable-3.5.2/test/shared_config.dart new file mode 100644 index 000000000..e8a38d5e0 --- /dev/null +++ b/json_serializable-3.5.2/test/shared_config.dart @@ -0,0 +1,25 @@ +// 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. + +import 'package:json_annotation/json_annotation.dart'; + +final jsonSerializableFields = generatorConfigDefaultJson.keys.toList(); + +final generatorConfigDefaultJson = Map<String, dynamic>.unmodifiable( + const JsonSerializable().withDefaults().toJson()); + +final generatorConfigNonDefaultJson = + Map<String, dynamic>.unmodifiable(const JsonSerializable( + anyMap: true, + checked: true, + createFactory: false, + createToJson: false, + disallowUnrecognizedKeys: true, + explicitToJson: true, + fieldRename: FieldRename.kebab, + ignoreUnannotated: true, + includeIfNull: false, + nullable: false, + genericArgumentFactories: true, +).toJson()); diff --git a/json_serializable-3.5.2/test/src/_json_serializable_test_input.dart b/json_serializable-3.5.2/test/src/_json_serializable_test_input.dart new file mode 100644 index 000000000..ca5b848c9 --- /dev/null +++ b/json_serializable-3.5.2/test/src/_json_serializable_test_input.dart @@ -0,0 +1,583 @@ +// 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. + +import 'dart:collection'; + +import 'package:json_annotation/json_annotation.dart'; +import 'package:json_serializable/src/helper_core.dart'; +import 'package:source_gen_test/annotations.dart'; + +part 'checked_test_input.dart'; + +part 'core_subclass_type_input.dart'; + +part 'default_value_input.dart'; + +part 'field_namer_input.dart'; + +part 'generic_test_input.dart'; + +part 'inheritance_test_input.dart'; + +part 'json_converter_test_input.dart'; + +part 'map_key_variety_test_input.dart'; + +part 'setter_test_input.dart'; + +part 'to_from_json_test_input.dart'; + +part 'unknown_enum_value_test_input.dart'; + +@ShouldThrow('`@JsonSerializable` can only be used on classes.') +@JsonSerializable() +const theAnswer = 42; + +@ShouldThrow('`@JsonSerializable` can only be used on classes.') +@JsonSerializable() +Object annotatedMethod() => null; + +@ShouldGenerate( + r''' +OnlyStaticMembers _$OnlyStaticMembersFromJson(Map<String, dynamic> json) { + return OnlyStaticMembers(); +} + +Map<String, dynamic> _$OnlyStaticMembersToJson(OnlyStaticMembers instance) => + <String, dynamic>{}; +''', + configurations: ['default'], +) +@JsonSerializable() +class OnlyStaticMembers { + // To ensure static members are not considered for serialization. + static const answer = 42; + static final reason = DateTime.now(); + + static int get understand => 42; +} + +@ShouldGenerate(r''' +GeneralTestClass1 _$GeneralTestClass1FromJson(Map<String, dynamic> json) { + return GeneralTestClass1() + ..firstName = json['firstName'] as String + ..lastName = json['lastName'] as String + ..height = json['h'] as int + ..dateOfBirth = json['dateOfBirth'] == null + ? null + : DateTime.parse(json['dateOfBirth'] as String) + ..dynamicType = json['dynamicType'] + ..varType = json['varType'] + ..listOfInts = (json['listOfInts'] as List)?.map((e) => e as int)?.toList(); +} + +Map<String, dynamic> _$GeneralTestClass1ToJson(GeneralTestClass1 instance) => + <String, dynamic>{ + 'firstName': instance.firstName, + 'lastName': instance.lastName, + 'h': instance.height, + 'dateOfBirth': instance.dateOfBirth?.toIso8601String(), + 'dynamicType': instance.dynamicType, + 'varType': instance.varType, + 'listOfInts': instance.listOfInts, + }; +''') +@JsonSerializable() +class GeneralTestClass1 { + String firstName, lastName; + @JsonKey(name: 'h') + int height; + DateTime dateOfBirth; + dynamic dynamicType; + + //ignore: prefer_typing_uninitialized_variables + var varType; + List<int> listOfInts; +} + +@ShouldGenerate(r''' +GeneralTestClass2 _$GeneralTestClass2FromJson(Map<String, dynamic> json) { + return GeneralTestClass2( + json['height'] as int, + json['firstName'] as String, + json['lastName'] as String, + )..dateOfBirth = json['dateOfBirth'] == null + ? null + : DateTime.parse(json['dateOfBirth'] as String); +} + +Map<String, dynamic> _$GeneralTestClass2ToJson(GeneralTestClass2 instance) => + <String, dynamic>{ + 'firstName': instance.firstName, + 'lastName': instance.lastName, + 'height': instance.height, + 'dateOfBirth': instance.dateOfBirth?.toIso8601String(), + }; +''') +@JsonSerializable() +class GeneralTestClass2 { + final String firstName, lastName; + int height; + DateTime dateOfBirth; + + GeneralTestClass2(this.height, String firstName, [this.lastName]) + : + // ignore: prefer_initializing_formals + firstName = firstName; +} + +@ShouldGenerate(r''' +FinalFields _$FinalFieldsFromJson(Map<String, dynamic> json) { + return FinalFields( + json['a'] as int, + ); +} + +Map<String, dynamic> _$FinalFieldsToJson(FinalFields instance) => + <String, dynamic>{ + 'a': instance.a, + }; +''') +@JsonSerializable() +class FinalFields { + final int a; + + int get b => 4; + + FinalFields(this.a); +} + +@ShouldGenerate( + r''' +FinalFieldsNotSetInCtor _$FinalFieldsNotSetInCtorFromJson( + Map<String, dynamic> json) { + return FinalFieldsNotSetInCtor(); +} + +Map<String, dynamic> _$FinalFieldsNotSetInCtorToJson( + FinalFieldsNotSetInCtor instance) => + <String, dynamic>{}; +''', + configurations: ['default'], +) +@JsonSerializable() +class FinalFieldsNotSetInCtor { + final int a = 1; + + FinalFieldsNotSetInCtor(); +} + +@ShouldGenerate(r''' +SetSupport _$SetSupportFromJson(Map<String, dynamic> json) { + return SetSupport( + (json['values'] as List)?.map((e) => e as int)?.toSet(), + ); +} + +Map<String, dynamic> _$SetSupportToJson(SetSupport instance) => + <String, dynamic>{ + 'values': instance.values?.toList(), + }; +''') +@JsonSerializable() +class SetSupport { + final Set<int> values; + + SetSupport(this.values); +} + +@ShouldThrow( + ''' +Could not generate `toJson` code for `watch`. +To support the type `Stopwatch` you can: +$converterOrKeyInstructions''', + configurations: ['default'], +) +@JsonSerializable(createFactory: false) +class NoSerializeFieldType { + Stopwatch watch; +} + +@ShouldThrow( + ''' +Could not generate `fromJson` code for `watch`. +To support the type `Stopwatch` you can: +$converterOrKeyInstructions''', + configurations: ['default'], +) +@JsonSerializable(createToJson: false) +class NoDeserializeFieldType { + Stopwatch watch; +} + +@ShouldThrow( + ''' +Could not generate `toJson` code for `durationDateTimeMap` because of type `Duration`. +Map keys must be one of: Object, dynamic, enum, String, BigInt, DateTime, int, Uri.''', + configurations: ['default'], +) +@JsonSerializable(createFactory: false) +class NoSerializeBadKey { + Map<Duration, DateTime> durationDateTimeMap; +} + +@ShouldThrow( + ''' +Could not generate `fromJson` code for `durationDateTimeMap` because of type `Duration`. +Map keys must be one of: Object, dynamic, enum, String, BigInt, DateTime, int, Uri.''', + configurations: ['default'], +) +@JsonSerializable(createToJson: false) +class NoDeserializeBadKey { + Map<Duration, DateTime> durationDateTimeMap; +} + +@ShouldGenerate( + r''' +Map<String, dynamic> _$IncludeIfNullOverrideToJson( + IncludeIfNullOverride instance) { + final val = <String, dynamic>{ + 'number': instance.number, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('str', instance.str); + return val; +} +''', + configurations: ['default'], +) +@JsonSerializable(createFactory: false, includeIfNull: false) +class IncludeIfNullOverride { + @JsonKey(includeIfNull: true) + int number; + String str; +} + +// https://github.com/google/json_serializable.dart/issues/7 regression +@ShouldThrow( + 'The class `NoCtorClass` has no default constructor.', + configurations: ['default'], +) +@JsonSerializable() +class NoCtorClass { + final int member; + + //ignore: avoid_unused_constructor_parameters + factory NoCtorClass.fromJson(Map<String, dynamic> json) => null; +} + +@ShouldThrow( + 'More than one field has the JSON key for name "str".', + element: 'str', +) +@JsonSerializable(createFactory: false) +class KeyDupesField { + @JsonKey(name: 'str') + int number; + + String str; +} + +@ShouldThrow( + 'More than one field has the JSON key for name "a".', + element: 'str', +) +@JsonSerializable(createFactory: false) +class DupeKeys { + @JsonKey(name: 'a') + int number; + + @JsonKey(name: 'a') + String str; +} + +@ShouldGenerate(r''' +Map<String, dynamic> _$IgnoredFieldClassToJson(IgnoredFieldClass instance) => + <String, dynamic>{ + 'ignoredFalseField': instance.ignoredFalseField, + 'ignoredNullField': instance.ignoredNullField, + }; +''') +@JsonSerializable(createFactory: false) +class IgnoredFieldClass { + @JsonKey(ignore: true) + int ignoredTrueField; + + @JsonKey(ignore: false) + int ignoredFalseField; + + int ignoredNullField; +} + +@ShouldThrow( + 'Cannot populate the required constructor argument: ' + 'ignoredTrueField. It is assigned to an ignored field.', + element: '', +) +@JsonSerializable() +class IgnoredFieldCtorClass { + @JsonKey(ignore: true) + int ignoredTrueField; + + IgnoredFieldCtorClass(this.ignoredTrueField); +} + +@ShouldThrow( + 'Cannot populate the required constructor argument: ' + '_privateField. It is assigned to a private field.', + element: '', +) +@JsonSerializable() +class PrivateFieldCtorClass { + // ignore: unused_field + final int _privateField; + + PrivateFieldCtorClass(this._privateField); +} + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. ' + 'Cannot set both `disallowNullvalue` and `includeIfNull` to `true`. ' + 'This leads to incompatible `toJson` and `fromJson` behavior.', + element: 'field', +) +@JsonSerializable() +class IncludeIfNullDisallowNullClass { + @JsonKey(includeIfNull: true, disallowNullValue: true) + int field; +} + +@ShouldThrow( + 'The `JsonValue` annotation on `BadEnum.value` does not have a value ' + 'of type String, int, or null.', + element: 'value', +) +@JsonSerializable() +class JsonValueWithBool { + BadEnum field; +} + +enum BadEnum { + @JsonValue(true) + value +} + +@ShouldGenerate(r'''const _$GoodEnumEnumMap = { + GoodEnum.noAnnotation: 'noAnnotation', + GoodEnum.stringAnnotation: 'string annotation', + GoodEnum.stringAnnotationWeird: r"string annotation with $ funky 'values'", + GoodEnum.intValue: 42, + GoodEnum.nullValue: null, +}; +''', contains: true) +@JsonSerializable() +class JsonValueValid { + GoodEnum field; +} + +enum GoodEnum { + noAnnotation, + @JsonValue('string annotation') + stringAnnotation, + @JsonValue("string annotation with \$ funky 'values'") + stringAnnotationWeird, + @JsonValue(42) + intValue, + @JsonValue(null) + nullValue +} + +@ShouldGenerate(r''' +FieldWithFromJsonCtorAndTypeParams _$FieldWithFromJsonCtorAndTypeParamsFromJson( + Map<String, dynamic> json) { + return FieldWithFromJsonCtorAndTypeParams() + ..customOrders = json['customOrders'] == null + ? null + : MyList.fromJson((json['customOrders'] as List) + ?.map((e) => e == null + ? null + : GeneralTestClass2.fromJson(e as Map<String, dynamic>)) + ?.toList()); +} +''') +@JsonSerializable(createToJson: false) +class FieldWithFromJsonCtorAndTypeParams { + MyList<GeneralTestClass2, int> customOrders; +} + +class MyList<T, Q> extends ListBase<T> { + final List<T> _data; + + MyList(Iterable<T> source) : _data = source.toList() ?? []; + + factory MyList.fromJson(List<T> items) => MyList(items); + + @override + int get length => _data.length; + + @override + set length(int value) { + _data.length = value; + } + + @override + T operator [](int index) => _data[index]; + + @override + void operator []=(int index, T value) { + _data[index] = value; + } +} + +mixin _PropInMixinI448RegressionMixin { + @JsonKey(nullable: true) + int nullable; +} + +@ShouldGenerate(r''' +PropInMixinI448Regression _$PropInMixinI448RegressionFromJson( + Map<String, dynamic> json) { + return PropInMixinI448Regression() + ..nullable = json['nullable'] as int + ..notNullable = json['notNullable'] as int; +} + +Map<String, dynamic> _$PropInMixinI448RegressionToJson( + PropInMixinI448Regression instance) => + <String, dynamic>{ + 'nullable': instance.nullable, + 'notNullable': instance.notNullable, + }; +''') +@JsonSerializable() +class PropInMixinI448Regression with _PropInMixinI448RegressionMixin { + @JsonKey(nullable: false) + int notNullable; +} + +@ShouldGenerate( + r''' +IgnoreUnannotated _$IgnoreUnannotatedFromJson(Map<String, dynamic> json) { + return IgnoreUnannotated()..annotated = json['annotated'] as int; +} + +Map<String, dynamic> _$IgnoreUnannotatedToJson(IgnoreUnannotated instance) => + <String, dynamic>{ + 'annotated': instance.annotated, + }; +''', +) +@JsonSerializable(ignoreUnannotated: true) +class IgnoreUnannotated { + @JsonKey() + int annotated; + + int unannotated; +} + +@ShouldGenerate( + r''' +SubclassedJsonKey _$SubclassedJsonKeyFromJson(Map<String, dynamic> json) { + return SubclassedJsonKey()..annotatedWithSubclass = json['bob'] as int; +} + +Map<String, dynamic> _$SubclassedJsonKeyToJson(SubclassedJsonKey instance) => + <String, dynamic>{ + 'bob': instance.annotatedWithSubclass, + }; +''', +) +@JsonSerializable(ignoreUnannotated: true) +class SubclassedJsonKey { + @MyJsonKey() + int annotatedWithSubclass; +} + +class MyJsonKey extends JsonKey { + const MyJsonKey() : super(name: 'bob'); +} + +@ShouldGenerate( + r''' +OverrideGetterExampleI613 _$OverrideGetterExampleI613FromJson( + Map<String, dynamic> json) { + return OverrideGetterExampleI613()..id = json['id'] as String; +} + +Map<String, dynamic> _$OverrideGetterExampleI613ToJson( + OverrideGetterExampleI613 instance) => + <String, dynamic>{ + 'id': instance.id, + }; +''', +) +@JsonSerializable(nullable: false) +class OverrideGetterExampleI613 extends OverrideGetterExampleI613Super { + @override + String get id => throw UnimplementedError(); +} + +class OverrideGetterExampleI613Super { + set id(String value) => throw UnimplementedError(); + + String get id => throw UnimplementedError(); +} + +@ShouldThrow( + 'Expecting a `fromJson` constructor with exactly one positional parameter. ' + 'Found a constructor with 0 parameters.', + element: 'fromJson', +) +@JsonSerializable() +class InvalidChildClassFromJson { + NoParamFromJsonCtor field; +} + +class NoParamFromJsonCtor { + NoParamFromJsonCtor.fromJson(); +} + +@ShouldThrow( + 'Expecting a `fromJson` constructor with exactly one positional parameter. ' + 'The only extra parameters allowed are functions of the form ' + '`T Function(Object) fromJsonT` ' + 'where `T` is a type parameter of the target type.', + element: 'fromJson', +) +@JsonSerializable() +class InvalidChildClassFromJson2 { + ExtraParamFromJsonCtor field; +} + +class ExtraParamFromJsonCtor { + // ignore: avoid_unused_constructor_parameters + ExtraParamFromJsonCtor.fromJson(Map<String, dynamic> json, int oops); + + Map<String, dynamic> toJson() => null; +} + +@ShouldThrow( + 'Expecting a `toJson` function with no required parameters. ' + 'The only extra parameters allowed are functions of the form ' + '`Object Function(T) toJsonT` where `T` is a type parameter of the target ' + ' type.', + element: 'toJson', +) +@JsonSerializable() +class InvalidChildClassFromJson3 { + ExtraParamToJson field; +} + +class ExtraParamToJson { + // ignore: avoid_unused_constructor_parameters + ExtraParamToJson.fromJson(Map<String, dynamic> json); + + Map<String, dynamic> toJson(int bob) => null; +} diff --git a/json_serializable-3.5.2/test/src/checked_test_input.dart b/json_serializable-3.5.2/test/src/checked_test_input.dart new file mode 100644 index 000000000..a7e6e151a --- /dev/null +++ b/json_serializable-3.5.2/test/src/checked_test_input.dart @@ -0,0 +1,52 @@ +part of '_json_serializable_test_input.dart'; + +@ShouldGenerate(r''' +WithANonCtorGetterChecked _$WithANonCtorGetterCheckedFromJson( + Map<String, dynamic> json) { + return $checkedNew('WithANonCtorGetterChecked', json, () { + $checkKeys(json, + allowedKeys: const ['items'], + requiredKeys: const ['items'], + disallowNullValues: const ['items']); + final val = WithANonCtorGetterChecked( + $checkedConvert( + json, 'items', (v) => (v as List)?.map((e) => e as String)?.toList()), + ); + return val; + }); +} +''') +@JsonSerializable( + disallowUnrecognizedKeys: true, + createToJson: false, + checked: true, +) +class WithANonCtorGetterChecked { + @JsonKey(required: true, disallowNullValue: true) + final List<String> items; + + int get length => items.length; + + WithANonCtorGetterChecked(this.items); +} + +@ShouldGenerate(r''' +WithANonCtorGetter _$WithANonCtorGetterFromJson(Map<String, dynamic> json) { + $checkKeys(json, + allowedKeys: const ['items'], + requiredKeys: const ['items'], + disallowNullValues: const ['items']); + return WithANonCtorGetter( + (json['items'] as List)?.map((e) => e as String)?.toList(), + ); +} +''') +@JsonSerializable(disallowUnrecognizedKeys: true, createToJson: false) +class WithANonCtorGetter { + @JsonKey(required: true, disallowNullValue: true) + final List<String> items; + + int get length => items.length; + + WithANonCtorGetter(this.items); +} diff --git a/json_serializable-3.5.2/test/src/core_subclass_type_input.dart b/json_serializable-3.5.2/test/src/core_subclass_type_input.dart new file mode 100644 index 000000000..bad046a8f --- /dev/null +++ b/json_serializable-3.5.2/test/src/core_subclass_type_input.dart @@ -0,0 +1,81 @@ +part of '_json_serializable_test_input.dart'; + +@ShouldThrow( + ''' +Could not generate `fromJson` code for `mapView`. +To support the type `MapView` you can: +$converterOrKeyInstructions''', + element: 'mapView', +) +@JsonSerializable(createToJson: false) +class UnsupportedMapField { + MapView mapView; +} + +@ShouldThrow( + ''' +Could not generate `fromJson` code for `listView`. +To support the type `UnmodifiableListView` you can: +$converterOrKeyInstructions''', + element: 'listView', +) +@JsonSerializable(createToJson: false) +class UnsupportedListField { + UnmodifiableListView listView; +} + +@ShouldThrow( + ''' +Could not generate `fromJson` code for `customSet`. +To support the type `_CustomSet` you can: +$converterOrKeyInstructions''', + element: 'customSet', +) +@JsonSerializable(createToJson: false) +class UnsupportedSetField { + _CustomSet customSet; +} + +abstract class _CustomSet implements Set {} + +@ShouldThrow( + ''' +Could not generate `fromJson` code for `customDuration`. +To support the type `_CustomDuration` you can: +$converterOrKeyInstructions''', + element: 'customDuration', +) +@JsonSerializable(createToJson: false) +class UnsupportedDurationField { + _CustomDuration customDuration; +} + +abstract class _CustomDuration implements Duration {} + +@ShouldThrow( + ''' +Could not generate `fromJson` code for `customUri`. +To support the type `_CustomUri` you can: +$converterOrKeyInstructions''', + element: 'customUri', +) +@JsonSerializable(createToJson: false) +class UnsupportedUriField { + _CustomUri customUri; +} + +abstract class _CustomUri implements Uri {} + +@ShouldThrow( + ''' +Could not generate `fromJson` code for `customDateTime`. +To support the type `_CustomDateTime` you can: +$converterOrKeyInstructions''', + element: 'customDateTime', +) +@JsonSerializable(createToJson: false) +class UnsupportedDateTimeField { + _CustomDateTime customDateTime; +} + +abstract class _CustomDateTime implements DateTime {} diff --git a/json_serializable-3.5.2/test/src/default_value_input.dart b/json_serializable-3.5.2/test/src/default_value_input.dart new file mode 100644 index 000000000..94c14cacb --- /dev/null +++ b/json_serializable-3.5.2/test/src/default_value_input.dart @@ -0,0 +1,184 @@ +// 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. + +part of '_json_serializable_test_input.dart'; + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. ' + '`defaultValue` is `Symbol`, it must be a literal.', + element: 'field', +) +@JsonSerializable() +class DefaultWithSymbol { + @JsonKey(defaultValue: #symbol) + Object field; + + DefaultWithSymbol(); +} + +int _function() => 42; + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. ' + '`defaultValue` is `Function`, it must be a literal.', + element: 'field', +) +@JsonSerializable() +class DefaultWithFunction { + @JsonKey(defaultValue: _function) + Object field; + + DefaultWithFunction(); +} + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. ' + '`defaultValue` is `Type`, it must be a literal.', + element: 'field', +) +@JsonSerializable() +class DefaultWithType { + @JsonKey(defaultValue: Object) + Object field; + + DefaultWithType(); +} + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. ' + '`defaultValue` is `Duration`, it must be a literal.', + element: 'field', +) +@JsonSerializable() +class DefaultWithConstObject { + @JsonKey(defaultValue: Duration()) + Object field; + + DefaultWithConstObject(); +} + +enum Enum { value } + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. ' + '`defaultValue` is `List > Enum`, it must be a literal.', + element: 'field', +) +@JsonSerializable() +class DefaultWithNestedEnum { + @JsonKey(defaultValue: [Enum.value]) + Object field; + + DefaultWithNestedEnum(); +} + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. ' + 'Cannot use `defaultValue` on a field with `nullable` false.', + element: 'field', +) +@JsonSerializable() +class DefaultWithNonNullableField { + @JsonKey(defaultValue: 42, nullable: false) + Object field; + + DefaultWithNonNullableField(); +} + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. ' + 'Cannot use `defaultValue` on a field with `nullable` false.', + element: 'field', +) +@JsonSerializable(nullable: false) +class DefaultWithNonNullableClass { + @JsonKey(defaultValue: 42) + Object field; + + DefaultWithNonNullableClass(); +} + +@ShouldGenerate( + r''' +DefaultWithToJsonClass _$DefaultWithToJsonClassFromJson( + Map<String, dynamic> json) { + return DefaultWithToJsonClass() + ..fieldDefaultValueToJson = DefaultWithToJsonClass._fromJson( + json['fieldDefaultValueToJson'] as String) ?? + 7; +} +''', + expectedLogItems: [ + ''' +The field `fieldDefaultValueToJson` has both `defaultValue` and `fromJson` defined which likely won't work for your scenario. +Instead of using `defaultValue`, set `nullable: false` and handle `null` in the `fromJson` function.''' + ], +) +@JsonSerializable(createToJson: false) +class DefaultWithToJsonClass { + @JsonKey(defaultValue: 7, fromJson: _fromJson) + int fieldDefaultValueToJson; + + DefaultWithToJsonClass(); + + static int _fromJson(String input) => 41; +} + +@ShouldGenerate( + r''' +DefaultWithDisallowNullRequiredClass + _$DefaultWithDisallowNullRequiredClassFromJson(Map<String, dynamic> json) { + $checkKeys(json, + requiredKeys: const ['theField'], disallowNullValues: const ['theField']); + return DefaultWithDisallowNullRequiredClass() + ..theField = json['theField'] as int ?? 7; +} +''', + expectedLogItems: [ + 'The `defaultValue` on field `theField` will have no effect because both ' + '`disallowNullValue` and `required` are set to `true`.', + ], +) +@JsonSerializable(createToJson: false) +class DefaultWithDisallowNullRequiredClass { + @JsonKey(defaultValue: 7, disallowNullValue: true, required: true) + int theField; + + DefaultWithDisallowNullRequiredClass(); +} + +@ShouldGenerate(r''' +DefaultDoubleConstants _$DefaultDoubleConstantsFromJson( + Map<String, dynamic> json) { + return DefaultDoubleConstants() + ..defaultNan = (json['defaultNan'] as num)?.toDouble() ?? double.nan + ..defaultNegativeInfinity = + (json['defaultNegativeInfinity'] as num)?.toDouble() ?? + double.negativeInfinity + ..defaultInfinity = + (json['defaultInfinity'] as num)?.toDouble() ?? double.infinity + ..defaultMinPositive = + (json['defaultMinPositive'] as num)?.toDouble() ?? 5e-324 + ..defaultMaxFinite = (json['defaultMaxFinite'] as num)?.toDouble() ?? + 1.7976931348623157e+308; +} +''') +@JsonSerializable(createToJson: false) +class DefaultDoubleConstants { + @JsonKey(defaultValue: double.nan) + double defaultNan; + @JsonKey(defaultValue: double.negativeInfinity) + double defaultNegativeInfinity; + @JsonKey(defaultValue: double.infinity) + double defaultInfinity; + + // Since these values can be represented as number literals, there is no + // special handling. Including them here for completeness, though. + @JsonKey(defaultValue: double.minPositive) + double defaultMinPositive; + @JsonKey(defaultValue: double.maxFinite) + double defaultMaxFinite; + + DefaultDoubleConstants(); +} diff --git a/json_serializable-3.5.2/test/src/field_namer_input.dart b/json_serializable-3.5.2/test/src/field_namer_input.dart new file mode 100644 index 000000000..f8ec3c66e --- /dev/null +++ b/json_serializable-3.5.2/test/src/field_namer_input.dart @@ -0,0 +1,61 @@ +part of '_json_serializable_test_input.dart'; + +@ShouldGenerate(r''' +Map<String, dynamic> _$FieldNamerNoneToJson(FieldNamerNone instance) => + <String, dynamic>{ + 'theField': instance.theField, + 'NAME_OVERRIDE': instance.nameOverride, + }; +''') +@JsonSerializable(fieldRename: FieldRename.none, createFactory: false) +class FieldNamerNone { + String theField; + + @JsonKey(name: 'NAME_OVERRIDE') + String nameOverride; +} + +@ShouldGenerate(r''' +Map<String, dynamic> _$FieldNamerKebabToJson(FieldNamerKebab instance) => + <String, dynamic>{ + 'the-field': instance.theField, + 'NAME_OVERRIDE': instance.nameOverride, + }; +''') +@JsonSerializable(fieldRename: FieldRename.kebab, createFactory: false) +class FieldNamerKebab { + String theField; + + @JsonKey(name: 'NAME_OVERRIDE') + String nameOverride; +} + +@ShouldGenerate(r''' +Map<String, dynamic> _$FieldNamerPascalToJson(FieldNamerPascal instance) => + <String, dynamic>{ + 'TheField': instance.theField, + 'NAME_OVERRIDE': instance.nameOverride, + }; +''') +@JsonSerializable(fieldRename: FieldRename.pascal, createFactory: false) +class FieldNamerPascal { + String theField; + + @JsonKey(name: 'NAME_OVERRIDE') + String nameOverride; +} + +@ShouldGenerate(r''' +Map<String, dynamic> _$FieldNamerSnakeToJson(FieldNamerSnake instance) => + <String, dynamic>{ + 'the_field': instance.theField, + 'NAME_OVERRIDE': instance.nameOverride, + }; +''') +@JsonSerializable(fieldRename: FieldRename.snake, createFactory: false) +class FieldNamerSnake { + String theField; + + @JsonKey(name: 'NAME_OVERRIDE') + String nameOverride; +} diff --git a/json_serializable-3.5.2/test/src/generic_test_input.dart b/json_serializable-3.5.2/test/src/generic_test_input.dart new file mode 100644 index 000000000..b8642c87c --- /dev/null +++ b/json_serializable-3.5.2/test/src/generic_test_input.dart @@ -0,0 +1,87 @@ +// 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. + +part of '_json_serializable_test_input.dart'; + +@ShouldThrow( + ''' +Could not generate `fromJson` code for `result` because of type `TResult` (type parameter). +To support type parameters (generic types) you can: +$converterOrKeyInstructions +* Set `JsonSerializable.genericArgumentFactories` to `true` + https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonSerializable/genericArgumentFactories.html''', + element: 'result', +) +@JsonSerializable() +class Issue713<TResult> { + List<TResult> result; +} + +@ShouldGenerate(r''' +GenericClass<T, S> _$GenericClassFromJson<T extends num, S>( + Map<String, dynamic> json) { + return GenericClass<T, S>() + ..fieldObject = _dataFromJson(json['fieldObject']) + ..fieldDynamic = _dataFromJson(json['fieldDynamic']) + ..fieldInt = _dataFromJson(json['fieldInt']) + ..fieldT = _dataFromJson(json['fieldT']) + ..fieldS = _dataFromJson(json['fieldS']); +} + +Map<String, dynamic> _$GenericClassToJson<T extends num, S>( + GenericClass<T, S> instance) => + <String, dynamic>{ + 'fieldObject': _dataToJson(instance.fieldObject), + 'fieldDynamic': _dataToJson(instance.fieldDynamic), + 'fieldInt': _dataToJson(instance.fieldInt), + 'fieldT': _dataToJson(instance.fieldT), + 'fieldS': _dataToJson(instance.fieldS), + }; +''') +@JsonSerializable() +class GenericClass<T extends num, S> { + @JsonKey(fromJson: _dataFromJson, toJson: _dataToJson) + Object fieldObject; + + @JsonKey(fromJson: _dataFromJson, toJson: _dataToJson) + dynamic fieldDynamic; + + @JsonKey(fromJson: _dataFromJson, toJson: _dataToJson) + int fieldInt; + + @JsonKey(fromJson: _dataFromJson, toJson: _dataToJson) + T fieldT; + + @JsonKey(fromJson: _dataFromJson, toJson: _dataToJson) + S fieldS; + + GenericClass(); +} + +T _dataFromJson<T extends num>(Object input) => null; + +Object _dataToJson<T extends num>(T input) => null; + +@ShouldGenerate( + r''' +GenericArgumentFactoriesFlagWithoutGenericType + _$GenericArgumentFactoriesFlagWithoutGenericTypeFromJson( + Map<String, dynamic> json) { + return GenericArgumentFactoriesFlagWithoutGenericType(); +} + +Map<String, dynamic> _$GenericArgumentFactoriesFlagWithoutGenericTypeToJson( + GenericArgumentFactoriesFlagWithoutGenericType instance) => + <String, dynamic>{}; +''', + expectedLogItems: [ + 'The class `GenericArgumentFactoriesFlagWithoutGenericType` is annotated ' + 'with `JsonSerializable` field `genericArgumentFactories: true`. ' + '`genericArgumentFactories: true` only affects classes with type ' + 'parameters. For classes without type parameters, the option is ' + 'ignored.', + ], +) +@JsonSerializable(genericArgumentFactories: true) +class GenericArgumentFactoriesFlagWithoutGenericType {} diff --git a/json_serializable-3.5.2/test/src/inheritance_test_input.dart b/json_serializable-3.5.2/test/src/inheritance_test_input.dart new file mode 100644 index 000000000..68be3de05 --- /dev/null +++ b/json_serializable-3.5.2/test/src/inheritance_test_input.dart @@ -0,0 +1,138 @@ +part of '_json_serializable_test_input.dart'; + +@ShouldGenerate(r''' +SubType _$SubTypeFromJson(Map<String, dynamic> json) { + return SubType( + json['subTypeViaCtor'] as int, + json['super-final-field'] as int, + ) + ..superReadWriteField = json['superReadWriteField'] as int + ..subTypeReadWrite = json['subTypeReadWrite'] as int; +} + +Map<String, dynamic> _$SubTypeToJson(SubType instance) { + final val = <String, dynamic>{ + 'super-final-field': instance.superFinalField, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('superReadWriteField', instance.superReadWriteField); + val['subTypeViaCtor'] = instance.subTypeViaCtor; + val['subTypeReadWrite'] = instance.subTypeReadWrite; + return val; +} +''') +@JsonSerializable() +class SubType extends SuperType { + final int subTypeViaCtor; + int subTypeReadWrite; + + SubType(this.subTypeViaCtor, int superFinalField) : super(superFinalField); +} + +// NOTE: `SuperType` is intentionally after `SubType` in the source file to +// validate field ordering semantics. +class SuperType { + @JsonKey(name: 'super-final-field', nullable: false) + final int superFinalField; + + @JsonKey(includeIfNull: false) + int superReadWriteField; + + SuperType(this.superFinalField); + + /// Add a property to try to throw-off the generator + /// Since `priceHalf` is final and not in the constructor, it will be excluded + int get priceHalf => priceFraction(2); + + /// Add a method to try to throw-off the generator + int priceFraction(int other) => + superFinalField == null ? null : superFinalField ~/ other; +} + +@ShouldGenerate(r''' +Map<String, dynamic> _$SubTypeWithAnnotatedFieldOverrideExtendsToJson( + SubTypeWithAnnotatedFieldOverrideExtends instance) { + final val = <String, dynamic>{ + 'super-final-field': instance.superFinalField, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('superReadWriteField', instance.superReadWriteField); + val['priceHalf'] = instance.priceHalf; + return val; +} +''') +@JsonSerializable(createFactory: false) +class SubTypeWithAnnotatedFieldOverrideExtends extends SuperType { + SubTypeWithAnnotatedFieldOverrideExtends(int superTypeViaCtor) + : super(superTypeViaCtor); +} + +@ShouldGenerate(r''' +Map<String, dynamic> + _$SubTypeWithAnnotatedFieldOverrideExtendsWithOverridesToJson( + SubTypeWithAnnotatedFieldOverrideExtendsWithOverrides instance) => + <String, dynamic>{ + 'priceHalf': instance.priceHalf, + 'superReadWriteField': instance.superReadWriteField, + 'super-final-field': instance.superFinalField, + }; +''') +@JsonSerializable(createFactory: false) +class SubTypeWithAnnotatedFieldOverrideExtendsWithOverrides extends SuperType { + SubTypeWithAnnotatedFieldOverrideExtendsWithOverrides(int superTypeViaCtor) + : super(superTypeViaCtor); + + /// The annotation applied here overrides the annotation in [SuperType]. + @JsonKey(includeIfNull: true) + @override + int get superReadWriteField => super.superReadWriteField; + + @override + set superReadWriteField(int value) { + super.superReadWriteField = value; + } + + /// The order is picked up by this override, but the annotation is still + /// applied from [SuperType]. + @override + int get superFinalField => super.superFinalField; +} + +@ShouldGenerate(r''' +Map<String, dynamic> _$SubTypeWithAnnotatedFieldOverrideImplementsToJson( + SubTypeWithAnnotatedFieldOverrideImplements instance) => + <String, dynamic>{ + 'superReadWriteField': instance.superReadWriteField, + 'superFinalField': instance.superFinalField, + }; +''') +@JsonSerializable(createFactory: false) +class SubTypeWithAnnotatedFieldOverrideImplements implements SuperType { + // Note the order of fields in the output is determined by this class + @override + int superReadWriteField; + + @JsonKey(ignore: true) + @override + int get priceHalf => 42; + + /// Since the relationship is `implements` no [JsonKey] values from + /// [SuperType] are honored. + @override + int get superFinalField => 42; + + @override + int priceFraction(int other) => other; +} diff --git a/json_serializable-3.5.2/test/src/json_converter_test_input.dart b/json_serializable-3.5.2/test/src/json_converter_test_input.dart new file mode 100644 index 000000000..988886941 --- /dev/null +++ b/json_serializable-3.5.2/test/src/json_converter_test_input.dart @@ -0,0 +1,194 @@ +// 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. + +part of '_json_serializable_test_input.dart'; + +@ShouldGenerate(r''' +JsonConverterNamedCtor<E> _$JsonConverterNamedCtorFromJson<E>( + Map<String, dynamic> json) { + return JsonConverterNamedCtor<E>() + ..value = const _DurationMillisecondConverter.named() + .fromJson(json['value'] as int) + ..genericValue = + _GenericConverter<E>.named().fromJson(json['genericValue'] as int) + ..keyAnnotationFirst = + JsonConverterNamedCtor._fromJson(json['keyAnnotationFirst'] as int); +} + +Map<String, dynamic> _$JsonConverterNamedCtorToJson<E>( + JsonConverterNamedCtor<E> instance) => + <String, dynamic>{ + 'value': + const _DurationMillisecondConverter.named().toJson(instance.value), + 'genericValue': + _GenericConverter<E>.named().toJson(instance.genericValue), + 'keyAnnotationFirst': + JsonConverterNamedCtor._toJson(instance.keyAnnotationFirst), + }; +''') +@JsonSerializable() +@_DurationMillisecondConverter.named() +@_GenericConverter.named() +class JsonConverterNamedCtor<E> { + Duration value; + E genericValue; + + // Field annotations have precedence over class annotations + @JsonKey(fromJson: _fromJson, toJson: _toJson) + Duration keyAnnotationFirst; + + static Duration _fromJson(int value) => null; + + static int _toJson(Duration object) => 42; +} + +@ShouldGenerate(r''' +JsonConvertOnField<E> _$JsonConvertOnFieldFromJson<E>( + Map<String, dynamic> json) { + return JsonConvertOnField<E>() + ..annotatedField = const _DurationMillisecondConverter() + .fromJson(json['annotatedField'] as int) + ..annotatedWithNamedCtor = const _DurationMillisecondConverter.named() + .fromJson(json['annotatedWithNamedCtor'] as int) + ..classAnnotatedWithField = + _durationConverter.fromJson(json['classAnnotatedWithField'] as int) + ..genericValue = + _GenericConverter<E>().fromJson(json['genericValue'] as int); +} + +Map<String, dynamic> _$JsonConvertOnFieldToJson<E>( + JsonConvertOnField<E> instance) => + <String, dynamic>{ + 'annotatedField': + const _DurationMillisecondConverter().toJson(instance.annotatedField), + 'annotatedWithNamedCtor': const _DurationMillisecondConverter.named() + .toJson(instance.annotatedWithNamedCtor), + 'classAnnotatedWithField': + _durationConverter.toJson(instance.classAnnotatedWithField), + 'genericValue': _GenericConverter<E>().toJson(instance.genericValue), + }; +''') +@JsonSerializable() +@_durationConverter +class JsonConvertOnField<E> { + @_DurationMillisecondConverter() + Duration annotatedField; + + @_DurationMillisecondConverter.named() + Duration annotatedWithNamedCtor; + + Duration classAnnotatedWithField; + + @_GenericConverter() + E genericValue; +} + +class _GenericConverter<T> implements JsonConverter<T, int> { + const _GenericConverter(); + + const _GenericConverter.named(); + + @override + T fromJson(int json) => null; + + @override + int toJson(T object) => 0; +} + +@ShouldThrow( + '`JsonConverter` implementations can have no more than one type argument. ' + '`_BadConverter` has 2.', + element: '_BadConverter', +) +@JsonSerializable() +@_BadConverter() +class JsonConverterWithBadTypeArg<T> { + T value; +} + +class _BadConverter<T, S> implements JsonConverter<S, int> { + const _BadConverter(); + + @override + S fromJson(int json) => null; + + @override + int toJson(S object) => 0; +} + +@ShouldThrow( + 'Found more than one matching converter for `Duration`.', + element: '', +) +@JsonSerializable() +@_durationConverter +@_DurationMillisecondConverter() +class JsonConverterDuplicateAnnotations { + Duration value; +} + +const _durationConverter = _DurationMillisecondConverter(); + +class _DurationMillisecondConverter implements JsonConverter<Duration, int> { + const _DurationMillisecondConverter(); + + const _DurationMillisecondConverter.named(); + + @override + Duration fromJson(int json) => + json == null ? null : Duration(milliseconds: json); + + @override + int toJson(Duration object) => object?.inMilliseconds; +} + +@ShouldThrow( + 'Generators with constructor arguments are not supported.', + element: '', +) +@JsonSerializable() +@_ConverterWithCtorParams(42) +class JsonConverterCtorParams { + Duration value; +} + +class _ConverterWithCtorParams implements JsonConverter<Duration, int> { + final int param; + + const _ConverterWithCtorParams(this.param); + + @override + Duration fromJson(int json) => null; + + @override + int toJson(Duration object) => 0; +} + +@ShouldGenerate(r''' +Map<String, dynamic> _$JsonConverterOnGetterToJson( + JsonConverterOnGetter instance) => + <String, dynamic>{ + 'annotatedGetter': + const _NeedsConversionConverter().toJson(instance.annotatedGetter), + }; +''') +@JsonSerializable(createFactory: false) +class JsonConverterOnGetter { + @JsonKey() + @_NeedsConversionConverter() + _NeedsConversion get annotatedGetter => _NeedsConversion(); +} + +class _NeedsConversion {} + +class _NeedsConversionConverter + implements JsonConverter<_NeedsConversion, int> { + const _NeedsConversionConverter(); + + @override + _NeedsConversion fromJson(int json) => _NeedsConversion(); + + @override + int toJson(_NeedsConversion object) => 0; +} diff --git a/json_serializable-3.5.2/test/src/map_key_variety_test_input.dart b/json_serializable-3.5.2/test/src/map_key_variety_test_input.dart new file mode 100644 index 000000000..41abe7029 --- /dev/null +++ b/json_serializable-3.5.2/test/src/map_key_variety_test_input.dart @@ -0,0 +1,19 @@ +part of '_json_serializable_test_input.dart'; + +@ShouldGenerate(r''' +MapKeyVariety _$MapKeyVarietyFromJson(Map<String, dynamic> json) { + return MapKeyVariety() + ..intIntMap = (json['intIntMap'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(int.parse(k), e as int), + ); +} + +Map<String, dynamic> _$MapKeyVarietyToJson(MapKeyVariety instance) => + <String, dynamic>{ + 'intIntMap': instance.intIntMap?.map((k, e) => MapEntry(k.toString(), e)), + }; +''') +@JsonSerializable() +class MapKeyVariety { + Map<int, int> intIntMap; +} diff --git a/json_serializable-3.5.2/test/src/setter_test_input.dart b/json_serializable-3.5.2/test/src/setter_test_input.dart new file mode 100644 index 000000000..b951dfeb5 --- /dev/null +++ b/json_serializable-3.5.2/test/src/setter_test_input.dart @@ -0,0 +1,46 @@ +part of '_json_serializable_test_input.dart'; + +@ShouldGenerate( + r''' +JustSetter _$JustSetterFromJson(Map<String, dynamic> json) { + return JustSetter(); +} + +Map<String, dynamic> _$JustSetterToJson(JustSetter instance) => + <String, dynamic>{}; +''', + expectedLogItems: ['Setters are ignored: JustSetter.someSetter'], + configurations: ['default'], +) +@JsonSerializable() +class JustSetter { + set someSetter(Object name) {} +} + +@ShouldGenerate( + r''' +JustSetterNoToJson _$JustSetterNoToJsonFromJson(Map<String, dynamic> json) { + return JustSetterNoToJson(); +} +''', + expectedLogItems: ['Setters are ignored: JustSetterNoToJson.someSetter'], + configurations: ['default'], +) +@JsonSerializable(createToJson: false) +class JustSetterNoToJson { + set someSetter(Object name) {} +} + +@ShouldGenerate( + r''' +Map<String, dynamic> _$JustSetterNoFromJsonToJson( + JustSetterNoFromJson instance) => + <String, dynamic>{}; +''', + expectedLogItems: ['Setters are ignored: JustSetterNoFromJson.someSetter'], + configurations: ['default'], +) +@JsonSerializable(createFactory: false) +class JustSetterNoFromJson { + set someSetter(Object name) {} +} diff --git a/json_serializable-3.5.2/test/src/to_from_json_test_input.dart b/json_serializable-3.5.2/test/src/to_from_json_test_input.dart new file mode 100644 index 000000000..c98d317bd --- /dev/null +++ b/json_serializable-3.5.2/test/src/to_from_json_test_input.dart @@ -0,0 +1,240 @@ +// 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. + +part of '_json_serializable_test_input.dart'; + +int _toInt(bool input) => 42; + +int _twoArgFunction(int a, int b) => 42; + +dynamic _toDynamic(dynamic input) => null; + +Object _toObject(Object input) => null; + +String _toStringFromObject(Object input) => null; + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. The `fromJson` function `_toInt` ' + 'return type `int` is not compatible with field type `String`.', + element: 'field', +) +@JsonSerializable() +class BadFromFuncReturnType { + @JsonKey(fromJson: _toInt) + String field; +} + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. The `fromJson` function ' + '`_twoArgFunction` must have one positional parameter.', + element: 'field', +) +@JsonSerializable() +class InvalidFromFunc2Args { + @JsonKey(fromJson: _twoArgFunction) + String field; +} + +@ShouldGenerate( + r''' +ValidToFromFuncClassStatic _$ValidToFromFuncClassStaticFromJson( + Map<String, dynamic> json) { + return ValidToFromFuncClassStatic() + ..field = ValidToFromFuncClassStatic._staticFunc(json['field'] as String); +} + +Map<String, dynamic> _$ValidToFromFuncClassStaticToJson( + ValidToFromFuncClassStatic instance) => + <String, dynamic>{ + 'field': ValidToFromFuncClassStatic._staticFunc(instance.field), + }; +''', + configurations: ['default'], +) +@JsonSerializable() +class ValidToFromFuncClassStatic { + static String _staticFunc(String param) => null; + + @JsonKey(fromJson: _staticFunc, toJson: _staticFunc) + String field; +} + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. The `toJson` function `_toInt` ' + 'argument type `bool` is not compatible with field type `String`.', + element: 'field', +) +@JsonSerializable() +class BadToFuncReturnType { + @JsonKey(toJson: _toInt) + String field; +} + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. The `toJson` function ' + '`_twoArgFunction` must have one positional parameter.', + element: 'field', +) +@JsonSerializable() +class InvalidToFunc2Args { + @JsonKey(toJson: _twoArgFunction) + String field; +} + +@ShouldGenerate( + "_toStringFromObject(json['field'])", + contains: true, +) +@JsonSerializable() +class ObjectConvertMethods { + @JsonKey(fromJson: _toStringFromObject, toJson: _toObject) + String field; +} + +@ShouldGenerate( + "_toDynamic(json['field'])", + contains: true, + configurations: ['default'], +) +@JsonSerializable() +class DynamicConvertMethods { + @JsonKey(fromJson: _toDynamic, toJson: _toDynamic) + String field; +} + +String _toString(String input) => null; + +@ShouldGenerate( + "_toString(json['field'] as String)", + contains: true, + configurations: ['default'], +) +@JsonSerializable() +class TypedConvertMethods { + @JsonKey(fromJson: _toString, toJson: _toString) + String field; +} + +@ShouldGenerate( + r''' +Map<String, dynamic> _$ToJsonNullableFalseIncludeIfNullFalseToJson( + ToJsonNullableFalseIncludeIfNullFalse instance) { + final val = <String, dynamic>{}; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('field', _toString(instance.field)); + return val; +} +''', + expectedLogItems: [ + 'The `JsonKey.nullable` value on ' + '`ToJsonNullableFalseIncludeIfNullFalse.field` will be ignored because ' + 'a custom conversion function is being used.', + ], + configurations: ['default'], +) +@JsonSerializable(createFactory: false) +class ToJsonNullableFalseIncludeIfNullFalse { + @JsonKey(toJson: _toString, includeIfNull: false, nullable: false) + String field; +} + +String _fromDynamicMap(Map input) => null; + +String _fromDynamicList(List input) => null; + +String _fromDynamicIterable(Iterable input) => null; + +@ShouldGenerate( + r''' +FromDynamicCollection _$FromDynamicCollectionFromJson( + Map<String, dynamic> json) { + return FromDynamicCollection() + ..mapField = _fromDynamicMap(json['mapField'] as Map) + ..listField = _fromDynamicList(json['listField'] as List) + ..iterableField = _fromDynamicIterable(json['iterableField'] as List); +} +''', + configurations: ['default'], +) +@JsonSerializable(createToJson: false) +class FromDynamicCollection { + @JsonKey(fromJson: _fromDynamicMap) + String mapField; + @JsonKey(fromJson: _fromDynamicList) + String listField; + @JsonKey(fromJson: _fromDynamicIterable) + String iterableField; +} + +String _noArgs() => null; + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. The `fromJson` function ' + '`_noArgs` must have one positional parameter.', + element: 'field', +) +@JsonSerializable(createToJson: false) +class BadNoArgs { + @JsonKey(fromJson: _noArgs) + String field; +} + +String _twoArgs(a, b) => null; + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. The `fromJson` function ' + '`_twoArgs` must have one positional parameter.', + element: 'field', +) +@JsonSerializable(createToJson: false) +class BadTwoRequiredPositional { + @JsonKey(fromJson: _twoArgs) + String field; +} + +String _oneNamed({a}) => null; + +@ShouldThrow( + 'Error with `@JsonKey` on `field`. The `fromJson` function ' + '`_oneNamed` must have one positional parameter.', + element: 'field', +) +@JsonSerializable(createToJson: false) +class BadOneNamed { + @JsonKey(fromJson: _oneNamed) + String field; +} + +String _oneNormalOnePositional(a, [b]) => null; + +@ShouldGenerate("_oneNormalOnePositional(json['field'])", contains: true) +@JsonSerializable(createToJson: false) +class OkayOneNormalOptionalPositional { + @JsonKey(fromJson: _oneNormalOnePositional) + String field; +} + +String _oneNormalOptionalNamed(a, {b}) => null; + +@ShouldGenerate("_oneNormalOptionalNamed(json['field'])", contains: true) +@JsonSerializable(createToJson: false) +class OkayOneNormalOptionalNamed { + @JsonKey(fromJson: _oneNormalOptionalNamed) + String field; +} + +String _onlyOptionalPositional([a, b]) => null; + +@ShouldGenerate("_onlyOptionalPositional(json['field'])", contains: true) +@JsonSerializable(createToJson: false) +class OkayOnlyOptionalPositional { + @JsonKey(fromJson: _onlyOptionalPositional) + String field; +} diff --git a/json_serializable-3.5.2/test/src/unknown_enum_value_test_input.dart b/json_serializable-3.5.2/test/src/unknown_enum_value_test_input.dart new file mode 100644 index 000000000..d156fa999 --- /dev/null +++ b/json_serializable-3.5.2/test/src/unknown_enum_value_test_input.dart @@ -0,0 +1,120 @@ +part of '_json_serializable_test_input.dart'; + +@ShouldGenerate( + r''' +UnknownEnumValue _$UnknownEnumValueFromJson(Map<String, dynamic> json) { + return UnknownEnumValue() + ..value = _$enumDecodeNullable( + _$UnknownEnumValueItemsEnumMap, json['value'], + unknownValue: UnknownEnumValueItems.vUnknown) ?? + UnknownEnumValueItems.vNull; +} + +T _$enumDecode<T>( + Map<T, dynamic> enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} + +T _$enumDecodeNullable<T>( + Map<T, dynamic> enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode<T>(enumValues, source, unknownValue: unknownValue); +} + +const _$UnknownEnumValueItemsEnumMap = { + UnknownEnumValueItems.v0: 'v0', + UnknownEnumValueItems.v1: 'v1', + UnknownEnumValueItems.v2: 'v2', + UnknownEnumValueItems.vUnknown: 'vUnknown', + UnknownEnumValueItems.vNull: 'vNull', +}; +''', +) +@JsonSerializable( + createToJson: false, +) +class UnknownEnumValue { + @JsonKey( + defaultValue: UnknownEnumValueItems.vNull, + unknownEnumValue: UnknownEnumValueItems.vUnknown, + ) + UnknownEnumValueItems value; +} + +enum UnknownEnumValueItems { v0, v1, v2, vUnknown, vNull } + +@ShouldThrow( + 'Error with `@JsonKey` on `value`. `unknownEnumValue` has type ' + '`int`, but the provided unknownEnumValue is of type ' + '`WrongEnumType`.', +) +@JsonSerializable() +class UnknownEnumValueListWrongType { + @JsonKey(unknownEnumValue: WrongEnumType.otherValue) + List<int> value; +} + +@ShouldThrow( + 'Error with `@JsonKey` on `value`. `unknownEnumValue` has type ' + '`UnknownEnumValueItems`, but the provided unknownEnumValue is of type ' + '`WrongEnumType`.', +) +@JsonSerializable() +class UnknownEnumValueListWrongEnumType { + @JsonKey(unknownEnumValue: WrongEnumType.otherValue) + List<UnknownEnumValueItems> value; +} + +enum WrongEnumType { otherValue } + +@ShouldThrow( + 'Error with `@JsonKey` on `value`. `unknownEnumValue` has type ' + '`UnknownEnumValueItems`, but the provided unknownEnumValue is of type ' + '`WrongEnumType`.', +) +@JsonSerializable() +class UnknownEnumValueWrongEnumType { + @JsonKey(unknownEnumValue: WrongEnumType.otherValue) + UnknownEnumValueItems value; +} + +@ShouldThrow( + 'Error with `@JsonKey` on `value`. The value provided ' + 'for `unknownEnumValue` must be a matching enum.', +) +@JsonSerializable() +class UnknownEnumValueNotEnumValue { + @JsonKey(unknownEnumValue: 'not enum value') + UnknownEnumValueItems value; +} + +@ShouldThrow( + 'Error with `@JsonKey` on `value`. `unknownEnumValue` can only be set on ' + 'fields of type enum or on Iterable, List, or Set instances of an enum type.', +) +@JsonSerializable() +class UnknownEnumValueNotEnumField { + @JsonKey(unknownEnumValue: UnknownEnumValueItems.vUnknown) + int value; +} diff --git a/json_serializable-3.5.2/test/supported_types/enum_type.dart b/json_serializable-3.5.2/test/supported_types/enum_type.dart new file mode 100644 index 000000000..360a6bf8e --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/enum_type.dart @@ -0,0 +1,5 @@ +// Copyright (c) 2020, 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. + +enum EnumType { alpha, beta, gamma, delta } diff --git a/json_serializable-3.5.2/test/supported_types/input.dart b/json_serializable-3.5.2/test/supported_types/input.dart new file mode 100644 index 000000000..61f84b8b5 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.dart @@ -0,0 +1,28 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'input.g.dart'; + +@JsonSerializable() +class SimpleClass { + final dynamic value; + + @JsonKey(nullable: false) + final dynamic nullable; + + @JsonKey(defaultValue: 42) + dynamic withDefault; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.g.dart b/json_serializable-3.5.2/test/supported_types/input.g.dart new file mode 100644 index 000000000..6200f9880 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.g.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'], + json['nullable'], + )..withDefault = json['withDefault'] ?? 42; +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + 'withDefault': instance.withDefault, + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_bigint.dart b/json_serializable-3.5.2/test/supported_types/input.type_bigint.dart new file mode 100644 index 000000000..af17f1a45 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_bigint.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'input.type_bigint.g.dart'; + +@JsonSerializable() +class SimpleClass { + final BigInt value; + + @JsonKey(nullable: false) + final BigInt nullable; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_bigint.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_bigint.g.dart new file mode 100644 index 000000000..f558a9326 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_bigint.g.dart @@ -0,0 +1,20 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_bigint.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'] == null ? null : BigInt.parse(json['value'] as String), + BigInt.parse(json['nullable'] as String), + ); +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value?.toString(), + 'nullable': instance.nullable.toString(), + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_bool.dart b/json_serializable-3.5.2/test/supported_types/input.type_bool.dart new file mode 100644 index 000000000..6d2b100be --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_bool.dart @@ -0,0 +1,28 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'input.type_bool.g.dart'; + +@JsonSerializable() +class SimpleClass { + final bool value; + + @JsonKey(nullable: false) + final bool nullable; + + @JsonKey(defaultValue: true) + bool withDefault; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_bool.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_bool.g.dart new file mode 100644 index 000000000..6b0bb40d7 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_bool.g.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_bool.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'] as bool, + json['nullable'] as bool, + )..withDefault = json['withDefault'] as bool ?? true; +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + 'withDefault': instance.withDefault, + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_datetime.dart b/json_serializable-3.5.2/test/supported_types/input.type_datetime.dart new file mode 100644 index 000000000..aae8b83db --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_datetime.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'input.type_datetime.g.dart'; + +@JsonSerializable() +class SimpleClass { + final DateTime value; + + @JsonKey(nullable: false) + final DateTime nullable; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_datetime.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_datetime.g.dart new file mode 100644 index 000000000..efb459777 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_datetime.g.dart @@ -0,0 +1,20 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_datetime.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'] == null ? null : DateTime.parse(json['value'] as String), + DateTime.parse(json['nullable'] as String), + ); +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value?.toIso8601String(), + 'nullable': instance.nullable.toIso8601String(), + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_double.dart b/json_serializable-3.5.2/test/supported_types/input.type_double.dart new file mode 100644 index 000000000..14a42481f --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_double.dart @@ -0,0 +1,28 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'input.type_double.g.dart'; + +@JsonSerializable() +class SimpleClass { + final double value; + + @JsonKey(nullable: false) + final double nullable; + + @JsonKey(defaultValue: 3.14) + double withDefault; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_double.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_double.g.dart new file mode 100644 index 000000000..36681b7d6 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_double.g.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_double.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + (json['value'] as num)?.toDouble(), + (json['nullable'] as num).toDouble(), + )..withDefault = (json['withDefault'] as num)?.toDouble() ?? 3.14; +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + 'withDefault': instance.withDefault, + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_duration.dart b/json_serializable-3.5.2/test/supported_types/input.type_duration.dart new file mode 100644 index 000000000..a38f9cd68 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_duration.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'input.type_duration.g.dart'; + +@JsonSerializable() +class SimpleClass { + final Duration value; + + @JsonKey(nullable: false) + final Duration nullable; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_duration.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_duration.g.dart new file mode 100644 index 000000000..f7a0bc777 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_duration.g.dart @@ -0,0 +1,20 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_duration.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'] == null ? null : Duration(microseconds: json['value'] as int), + Duration(microseconds: json['nullable'] as int), + ); +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value?.inMicroseconds, + 'nullable': instance.nullable.inMicroseconds, + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_enumtype.dart b/json_serializable-3.5.2/test/supported_types/input.type_enumtype.dart new file mode 100644 index 000000000..8c54e81d4 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_enumtype.dart @@ -0,0 +1,29 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; +import 'enum_type.dart'; + +part 'input.type_enumtype.g.dart'; + +@JsonSerializable() +class SimpleClass { + final EnumType value; + + @JsonKey(nullable: false) + final EnumType nullable; + + @JsonKey(defaultValue: EnumType.alpha) + EnumType withDefault; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_enumtype.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_enumtype.g.dart new file mode 100644 index 000000000..d79199ce6 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_enumtype.g.dart @@ -0,0 +1,62 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_enumtype.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + _$enumDecodeNullable(_$EnumTypeEnumMap, json['value']), + _$enumDecode(_$EnumTypeEnumMap, json['nullable']), + )..withDefault = + _$enumDecodeNullable(_$EnumTypeEnumMap, json['withDefault']) ?? + EnumType.alpha; +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': _$EnumTypeEnumMap[instance.value], + 'nullable': _$EnumTypeEnumMap[instance.nullable], + 'withDefault': _$EnumTypeEnumMap[instance.withDefault], + }; + +T _$enumDecode<T>( + Map<T, dynamic> enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} + +T _$enumDecodeNullable<T>( + Map<T, dynamic> enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode<T>(enumValues, source, unknownValue: unknownValue); +} + +const _$EnumTypeEnumMap = { + EnumType.alpha: 'alpha', + EnumType.beta: 'beta', + EnumType.gamma: 'gamma', + EnumType.delta: 'delta', +}; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_int.dart b/json_serializable-3.5.2/test/supported_types/input.type_int.dart new file mode 100644 index 000000000..42eb0e342 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_int.dart @@ -0,0 +1,28 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'input.type_int.g.dart'; + +@JsonSerializable() +class SimpleClass { + final int value; + + @JsonKey(nullable: false) + final int nullable; + + @JsonKey(defaultValue: 42) + int withDefault; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_int.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_int.g.dart new file mode 100644 index 000000000..99f4b297a --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_int.g.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_int.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'] as int, + json['nullable'] as int, + )..withDefault = json['withDefault'] as int ?? 42; +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + 'withDefault': instance.withDefault, + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_iterable.dart b/json_serializable-3.5.2/test/supported_types/input.type_iterable.dart new file mode 100644 index 000000000..0ba7d5f3c --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_iterable.dart @@ -0,0 +1,245 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; +import 'enum_type.dart'; + +part 'input.type_iterable.g.dart'; + +@JsonSerializable() +class SimpleClass { + final Iterable value; + + @JsonKey(nullable: false) + final Iterable nullable; + + @JsonKey(defaultValue: [42, true, false, null]) + Iterable withDefault; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} + +@JsonSerializable() +class SimpleClassBigInt { + final Iterable<BigInt> value; + + @JsonKey(nullable: false) + final Iterable<BigInt> nullable; + + SimpleClassBigInt( + this.value, + this.nullable, + ); + + factory SimpleClassBigInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToJson(this); +} + +@JsonSerializable() +class SimpleClassBool { + final Iterable<bool> value; + + @JsonKey(nullable: false) + final Iterable<bool> nullable; + + SimpleClassBool( + this.value, + this.nullable, + ); + + factory SimpleClassBool.fromJson(Map<String, dynamic> json) => + _$SimpleClassBoolFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBoolToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTime { + final Iterable<DateTime> value; + + @JsonKey(nullable: false) + final Iterable<DateTime> nullable; + + SimpleClassDateTime( + this.value, + this.nullable, + ); + + factory SimpleClassDateTime.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToJson(this); +} + +@JsonSerializable() +class SimpleClassDouble { + final Iterable<double> value; + + @JsonKey(nullable: false) + final Iterable<double> nullable; + + SimpleClassDouble( + this.value, + this.nullable, + ); + + factory SimpleClassDouble.fromJson(Map<String, dynamic> json) => + _$SimpleClassDoubleFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDoubleToJson(this); +} + +@JsonSerializable() +class SimpleClassDuration { + final Iterable<Duration> value; + + @JsonKey(nullable: false) + final Iterable<Duration> nullable; + + SimpleClassDuration( + this.value, + this.nullable, + ); + + factory SimpleClassDuration.fromJson(Map<String, dynamic> json) => + _$SimpleClassDurationFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDurationToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamic { + final Iterable<dynamic> value; + + @JsonKey(nullable: false) + final Iterable<dynamic> nullable; + + SimpleClassDynamic( + this.value, + this.nullable, + ); + + factory SimpleClassDynamic.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumType { + final Iterable<EnumType> value; + + @JsonKey(nullable: false) + final Iterable<EnumType> nullable; + + SimpleClassEnumType( + this.value, + this.nullable, + ); + + factory SimpleClassEnumType.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToJson(this); +} + +@JsonSerializable() +class SimpleClassInt { + final Iterable<int> value; + + @JsonKey(nullable: false) + final Iterable<int> nullable; + + SimpleClassInt( + this.value, + this.nullable, + ); + + factory SimpleClassInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToJson(this); +} + +@JsonSerializable() +class SimpleClassNum { + final Iterable<num> value; + + @JsonKey(nullable: false) + final Iterable<num> nullable; + + SimpleClassNum( + this.value, + this.nullable, + ); + + factory SimpleClassNum.fromJson(Map<String, dynamic> json) => + _$SimpleClassNumFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassNumToJson(this); +} + +@JsonSerializable() +class SimpleClassObject { + final Iterable<Object> value; + + @JsonKey(nullable: false) + final Iterable<Object> nullable; + + SimpleClassObject( + this.value, + this.nullable, + ); + + factory SimpleClassObject.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToJson(this); +} + +@JsonSerializable() +class SimpleClassString { + final Iterable<String> value; + + @JsonKey(nullable: false) + final Iterable<String> nullable; + + SimpleClassString( + this.value, + this.nullable, + ); + + factory SimpleClassString.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToJson(this); +} + +@JsonSerializable() +class SimpleClassUri { + final Iterable<Uri> value; + + @JsonKey(nullable: false) + final Iterable<Uri> nullable; + + SimpleClassUri( + this.value, + this.nullable, + ); + + factory SimpleClassUri.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_iterable.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_iterable.g.dart new file mode 100644 index 000000000..474f8ce78 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_iterable.g.dart @@ -0,0 +1,224 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_iterable.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'] as List, + json['nullable'] as List, + )..withDefault = json['withDefault'] as List ?? [42, true, false, null]; +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + 'withDefault': instance.withDefault?.toList(), + }; + +SimpleClassBigInt _$SimpleClassBigIntFromJson(Map<String, dynamic> json) { + return SimpleClassBigInt( + (json['value'] as List) + ?.map((e) => e == null ? null : BigInt.parse(e as String)), + (json['nullable'] as List).map((e) => BigInt.parse(e as String)), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToJson(SimpleClassBigInt instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => e?.toString())?.toList(), + 'nullable': instance.nullable.map((e) => e.toString()).toList(), + }; + +SimpleClassBool _$SimpleClassBoolFromJson(Map<String, dynamic> json) { + return SimpleClassBool( + (json['value'] as List)?.map((e) => e as bool), + (json['nullable'] as List).map((e) => e as bool), + ); +} + +Map<String, dynamic> _$SimpleClassBoolToJson(SimpleClassBool instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassDateTime _$SimpleClassDateTimeFromJson(Map<String, dynamic> json) { + return SimpleClassDateTime( + (json['value'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)), + (json['nullable'] as List).map((e) => DateTime.parse(e as String)), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToJson( + SimpleClassDateTime instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => e?.toIso8601String())?.toList(), + 'nullable': instance.nullable.map((e) => e.toIso8601String()).toList(), + }; + +SimpleClassDouble _$SimpleClassDoubleFromJson(Map<String, dynamic> json) { + return SimpleClassDouble( + (json['value'] as List)?.map((e) => (e as num)?.toDouble()), + (json['nullable'] as List).map((e) => (e as num).toDouble()), + ); +} + +Map<String, dynamic> _$SimpleClassDoubleToJson(SimpleClassDouble instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassDuration _$SimpleClassDurationFromJson(Map<String, dynamic> json) { + return SimpleClassDuration( + (json['value'] as List) + ?.map((e) => e == null ? null : Duration(microseconds: e as int)), + (json['nullable'] as List).map((e) => Duration(microseconds: e as int)), + ); +} + +Map<String, dynamic> _$SimpleClassDurationToJson( + SimpleClassDuration instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => e?.inMicroseconds)?.toList(), + 'nullable': instance.nullable.map((e) => e.inMicroseconds).toList(), + }; + +SimpleClassDynamic _$SimpleClassDynamicFromJson(Map<String, dynamic> json) { + return SimpleClassDynamic( + json['value'] as List, + json['nullable'] as List, + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToJson(SimpleClassDynamic instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassEnumType _$SimpleClassEnumTypeFromJson(Map<String, dynamic> json) { + return SimpleClassEnumType( + (json['value'] as List) + ?.map((e) => _$enumDecodeNullable(_$EnumTypeEnumMap, e)), + (json['nullable'] as List).map((e) => _$enumDecode(_$EnumTypeEnumMap, e)), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToJson( + SimpleClassEnumType instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => _$EnumTypeEnumMap[e])?.toList(), + 'nullable': instance.nullable.map((e) => _$EnumTypeEnumMap[e]).toList(), + }; + +T _$enumDecode<T>( + Map<T, dynamic> enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} + +T _$enumDecodeNullable<T>( + Map<T, dynamic> enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode<T>(enumValues, source, unknownValue: unknownValue); +} + +const _$EnumTypeEnumMap = { + EnumType.alpha: 'alpha', + EnumType.beta: 'beta', + EnumType.gamma: 'gamma', + EnumType.delta: 'delta', +}; + +SimpleClassInt _$SimpleClassIntFromJson(Map<String, dynamic> json) { + return SimpleClassInt( + (json['value'] as List)?.map((e) => e as int), + (json['nullable'] as List).map((e) => e as int), + ); +} + +Map<String, dynamic> _$SimpleClassIntToJson(SimpleClassInt instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassNum _$SimpleClassNumFromJson(Map<String, dynamic> json) { + return SimpleClassNum( + (json['value'] as List)?.map((e) => e as num), + (json['nullable'] as List).map((e) => e as num), + ); +} + +Map<String, dynamic> _$SimpleClassNumToJson(SimpleClassNum instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassObject _$SimpleClassObjectFromJson(Map<String, dynamic> json) { + return SimpleClassObject( + json['value'] as List, + json['nullable'] as List, + ); +} + +Map<String, dynamic> _$SimpleClassObjectToJson(SimpleClassObject instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassString _$SimpleClassStringFromJson(Map<String, dynamic> json) { + return SimpleClassString( + (json['value'] as List)?.map((e) => e as String), + (json['nullable'] as List).map((e) => e as String), + ); +} + +Map<String, dynamic> _$SimpleClassStringToJson(SimpleClassString instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassUri _$SimpleClassUriFromJson(Map<String, dynamic> json) { + return SimpleClassUri( + (json['value'] as List) + ?.map((e) => e == null ? null : Uri.parse(e as String)), + (json['nullable'] as List).map((e) => Uri.parse(e as String)), + ); +} + +Map<String, dynamic> _$SimpleClassUriToJson(SimpleClassUri instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => e?.toString())?.toList(), + 'nullable': instance.nullable.map((e) => e.toString()).toList(), + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_list.dart b/json_serializable-3.5.2/test/supported_types/input.type_list.dart new file mode 100644 index 000000000..44219ef49 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_list.dart @@ -0,0 +1,245 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; +import 'enum_type.dart'; + +part 'input.type_list.g.dart'; + +@JsonSerializable() +class SimpleClass { + final List value; + + @JsonKey(nullable: false) + final List nullable; + + @JsonKey(defaultValue: [42, true, false, null]) + List withDefault; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} + +@JsonSerializable() +class SimpleClassBigInt { + final List<BigInt> value; + + @JsonKey(nullable: false) + final List<BigInt> nullable; + + SimpleClassBigInt( + this.value, + this.nullable, + ); + + factory SimpleClassBigInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToJson(this); +} + +@JsonSerializable() +class SimpleClassBool { + final List<bool> value; + + @JsonKey(nullable: false) + final List<bool> nullable; + + SimpleClassBool( + this.value, + this.nullable, + ); + + factory SimpleClassBool.fromJson(Map<String, dynamic> json) => + _$SimpleClassBoolFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBoolToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTime { + final List<DateTime> value; + + @JsonKey(nullable: false) + final List<DateTime> nullable; + + SimpleClassDateTime( + this.value, + this.nullable, + ); + + factory SimpleClassDateTime.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToJson(this); +} + +@JsonSerializable() +class SimpleClassDouble { + final List<double> value; + + @JsonKey(nullable: false) + final List<double> nullable; + + SimpleClassDouble( + this.value, + this.nullable, + ); + + factory SimpleClassDouble.fromJson(Map<String, dynamic> json) => + _$SimpleClassDoubleFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDoubleToJson(this); +} + +@JsonSerializable() +class SimpleClassDuration { + final List<Duration> value; + + @JsonKey(nullable: false) + final List<Duration> nullable; + + SimpleClassDuration( + this.value, + this.nullable, + ); + + factory SimpleClassDuration.fromJson(Map<String, dynamic> json) => + _$SimpleClassDurationFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDurationToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamic { + final List<dynamic> value; + + @JsonKey(nullable: false) + final List<dynamic> nullable; + + SimpleClassDynamic( + this.value, + this.nullable, + ); + + factory SimpleClassDynamic.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumType { + final List<EnumType> value; + + @JsonKey(nullable: false) + final List<EnumType> nullable; + + SimpleClassEnumType( + this.value, + this.nullable, + ); + + factory SimpleClassEnumType.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToJson(this); +} + +@JsonSerializable() +class SimpleClassInt { + final List<int> value; + + @JsonKey(nullable: false) + final List<int> nullable; + + SimpleClassInt( + this.value, + this.nullable, + ); + + factory SimpleClassInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToJson(this); +} + +@JsonSerializable() +class SimpleClassNum { + final List<num> value; + + @JsonKey(nullable: false) + final List<num> nullable; + + SimpleClassNum( + this.value, + this.nullable, + ); + + factory SimpleClassNum.fromJson(Map<String, dynamic> json) => + _$SimpleClassNumFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassNumToJson(this); +} + +@JsonSerializable() +class SimpleClassObject { + final List<Object> value; + + @JsonKey(nullable: false) + final List<Object> nullable; + + SimpleClassObject( + this.value, + this.nullable, + ); + + factory SimpleClassObject.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToJson(this); +} + +@JsonSerializable() +class SimpleClassString { + final List<String> value; + + @JsonKey(nullable: false) + final List<String> nullable; + + SimpleClassString( + this.value, + this.nullable, + ); + + factory SimpleClassString.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToJson(this); +} + +@JsonSerializable() +class SimpleClassUri { + final List<Uri> value; + + @JsonKey(nullable: false) + final List<Uri> nullable; + + SimpleClassUri( + this.value, + this.nullable, + ); + + factory SimpleClassUri.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_list.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_list.g.dart new file mode 100644 index 000000000..bcedf4688 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_list.g.dart @@ -0,0 +1,233 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_list.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'] as List, + json['nullable'] as List, + )..withDefault = json['withDefault'] as List ?? [42, true, false, null]; +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + 'withDefault': instance.withDefault, + }; + +SimpleClassBigInt _$SimpleClassBigIntFromJson(Map<String, dynamic> json) { + return SimpleClassBigInt( + (json['value'] as List) + ?.map((e) => e == null ? null : BigInt.parse(e as String)) + ?.toList(), + (json['nullable'] as List).map((e) => BigInt.parse(e as String)).toList(), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToJson(SimpleClassBigInt instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => e?.toString())?.toList(), + 'nullable': instance.nullable.map((e) => e.toString()).toList(), + }; + +SimpleClassBool _$SimpleClassBoolFromJson(Map<String, dynamic> json) { + return SimpleClassBool( + (json['value'] as List)?.map((e) => e as bool)?.toList(), + (json['nullable'] as List).map((e) => e as bool).toList(), + ); +} + +Map<String, dynamic> _$SimpleClassBoolToJson(SimpleClassBool instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassDateTime _$SimpleClassDateTimeFromJson(Map<String, dynamic> json) { + return SimpleClassDateTime( + (json['value'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)) + ?.toList(), + (json['nullable'] as List).map((e) => DateTime.parse(e as String)).toList(), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToJson( + SimpleClassDateTime instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => e?.toIso8601String())?.toList(), + 'nullable': instance.nullable.map((e) => e.toIso8601String()).toList(), + }; + +SimpleClassDouble _$SimpleClassDoubleFromJson(Map<String, dynamic> json) { + return SimpleClassDouble( + (json['value'] as List)?.map((e) => (e as num)?.toDouble())?.toList(), + (json['nullable'] as List).map((e) => (e as num).toDouble()).toList(), + ); +} + +Map<String, dynamic> _$SimpleClassDoubleToJson(SimpleClassDouble instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassDuration _$SimpleClassDurationFromJson(Map<String, dynamic> json) { + return SimpleClassDuration( + (json['value'] as List) + ?.map((e) => e == null ? null : Duration(microseconds: e as int)) + ?.toList(), + (json['nullable'] as List) + .map((e) => Duration(microseconds: e as int)) + .toList(), + ); +} + +Map<String, dynamic> _$SimpleClassDurationToJson( + SimpleClassDuration instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => e?.inMicroseconds)?.toList(), + 'nullable': instance.nullable.map((e) => e.inMicroseconds).toList(), + }; + +SimpleClassDynamic _$SimpleClassDynamicFromJson(Map<String, dynamic> json) { + return SimpleClassDynamic( + json['value'] as List, + json['nullable'] as List, + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToJson(SimpleClassDynamic instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassEnumType _$SimpleClassEnumTypeFromJson(Map<String, dynamic> json) { + return SimpleClassEnumType( + (json['value'] as List) + ?.map((e) => _$enumDecodeNullable(_$EnumTypeEnumMap, e)) + ?.toList(), + (json['nullable'] as List) + .map((e) => _$enumDecode(_$EnumTypeEnumMap, e)) + .toList(), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToJson( + SimpleClassEnumType instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => _$EnumTypeEnumMap[e])?.toList(), + 'nullable': instance.nullable.map((e) => _$EnumTypeEnumMap[e]).toList(), + }; + +T _$enumDecode<T>( + Map<T, dynamic> enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} + +T _$enumDecodeNullable<T>( + Map<T, dynamic> enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode<T>(enumValues, source, unknownValue: unknownValue); +} + +const _$EnumTypeEnumMap = { + EnumType.alpha: 'alpha', + EnumType.beta: 'beta', + EnumType.gamma: 'gamma', + EnumType.delta: 'delta', +}; + +SimpleClassInt _$SimpleClassIntFromJson(Map<String, dynamic> json) { + return SimpleClassInt( + (json['value'] as List)?.map((e) => e as int)?.toList(), + (json['nullable'] as List).map((e) => e as int).toList(), + ); +} + +Map<String, dynamic> _$SimpleClassIntToJson(SimpleClassInt instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassNum _$SimpleClassNumFromJson(Map<String, dynamic> json) { + return SimpleClassNum( + (json['value'] as List)?.map((e) => e as num)?.toList(), + (json['nullable'] as List).map((e) => e as num).toList(), + ); +} + +Map<String, dynamic> _$SimpleClassNumToJson(SimpleClassNum instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassObject _$SimpleClassObjectFromJson(Map<String, dynamic> json) { + return SimpleClassObject( + json['value'] as List, + json['nullable'] as List, + ); +} + +Map<String, dynamic> _$SimpleClassObjectToJson(SimpleClassObject instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassString _$SimpleClassStringFromJson(Map<String, dynamic> json) { + return SimpleClassString( + (json['value'] as List)?.map((e) => e as String)?.toList(), + (json['nullable'] as List).map((e) => e as String).toList(), + ); +} + +Map<String, dynamic> _$SimpleClassStringToJson(SimpleClassString instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassUri _$SimpleClassUriFromJson(Map<String, dynamic> json) { + return SimpleClassUri( + (json['value'] as List) + ?.map((e) => e == null ? null : Uri.parse(e as String)) + ?.toList(), + (json['nullable'] as List).map((e) => Uri.parse(e as String)).toList(), + ); +} + +Map<String, dynamic> _$SimpleClassUriToJson(SimpleClassUri instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => e?.toString())?.toList(), + 'nullable': instance.nullable.map((e) => e.toString()).toList(), + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_map.dart b/json_serializable-3.5.2/test/supported_types/input.type_map.dart new file mode 100644 index 000000000..8b351b6fc --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_map.dart @@ -0,0 +1,1757 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; +import 'enum_type.dart'; + +part 'input.type_map.g.dart'; + +@JsonSerializable() +class SimpleClass { + final Map value; + + @JsonKey(nullable: false) + final Map nullable; + + @JsonKey(defaultValue: {'a': 1}) + Map withDefault; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} + +@JsonSerializable() +class SimpleClassBigIntToBigInt { + final Map<BigInt, BigInt> value; + + @JsonKey(nullable: false) + final Map<BigInt, BigInt> nullable; + + SimpleClassBigIntToBigInt( + this.value, + this.nullable, + ); + + factory SimpleClassBigIntToBigInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntToBigIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToBigIntToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTimeToBigInt { + final Map<DateTime, BigInt> value; + + @JsonKey(nullable: false) + final Map<DateTime, BigInt> nullable; + + SimpleClassDateTimeToBigInt( + this.value, + this.nullable, + ); + + factory SimpleClassDateTimeToBigInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeToBigIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToBigIntToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamicToBigInt { + final Map<dynamic, BigInt> value; + + @JsonKey(nullable: false) + final Map<dynamic, BigInt> nullable; + + SimpleClassDynamicToBigInt( + this.value, + this.nullable, + ); + + factory SimpleClassDynamicToBigInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicToBigIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToBigIntToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumTypeToBigInt { + final Map<EnumType, BigInt> value; + + @JsonKey(nullable: false) + final Map<EnumType, BigInt> nullable; + + SimpleClassEnumTypeToBigInt( + this.value, + this.nullable, + ); + + factory SimpleClassEnumTypeToBigInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeToBigIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToBigIntToJson(this); +} + +@JsonSerializable() +class SimpleClassIntToBigInt { + final Map<int, BigInt> value; + + @JsonKey(nullable: false) + final Map<int, BigInt> nullable; + + SimpleClassIntToBigInt( + this.value, + this.nullable, + ); + + factory SimpleClassIntToBigInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntToBigIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToBigIntToJson(this); +} + +@JsonSerializable() +class SimpleClassObjectToBigInt { + final Map<Object, BigInt> value; + + @JsonKey(nullable: false) + final Map<Object, BigInt> nullable; + + SimpleClassObjectToBigInt( + this.value, + this.nullable, + ); + + factory SimpleClassObjectToBigInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectToBigIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToBigIntToJson(this); +} + +@JsonSerializable() +class SimpleClassStringToBigInt { + final Map<String, BigInt> value; + + @JsonKey(nullable: false) + final Map<String, BigInt> nullable; + + SimpleClassStringToBigInt( + this.value, + this.nullable, + ); + + factory SimpleClassStringToBigInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringToBigIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToBigIntToJson(this); +} + +@JsonSerializable() +class SimpleClassUriToBigInt { + final Map<Uri, BigInt> value; + + @JsonKey(nullable: false) + final Map<Uri, BigInt> nullable; + + SimpleClassUriToBigInt( + this.value, + this.nullable, + ); + + factory SimpleClassUriToBigInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriToBigIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToBigIntToJson(this); +} + +@JsonSerializable() +class SimpleClassBigIntToBool { + final Map<BigInt, bool> value; + + @JsonKey(nullable: false) + final Map<BigInt, bool> nullable; + + SimpleClassBigIntToBool( + this.value, + this.nullable, + ); + + factory SimpleClassBigIntToBool.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntToBoolFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToBoolToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTimeToBool { + final Map<DateTime, bool> value; + + @JsonKey(nullable: false) + final Map<DateTime, bool> nullable; + + SimpleClassDateTimeToBool( + this.value, + this.nullable, + ); + + factory SimpleClassDateTimeToBool.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeToBoolFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToBoolToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamicToBool { + final Map<dynamic, bool> value; + + @JsonKey(nullable: false) + final Map<dynamic, bool> nullable; + + SimpleClassDynamicToBool( + this.value, + this.nullable, + ); + + factory SimpleClassDynamicToBool.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicToBoolFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToBoolToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumTypeToBool { + final Map<EnumType, bool> value; + + @JsonKey(nullable: false) + final Map<EnumType, bool> nullable; + + SimpleClassEnumTypeToBool( + this.value, + this.nullable, + ); + + factory SimpleClassEnumTypeToBool.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeToBoolFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToBoolToJson(this); +} + +@JsonSerializable() +class SimpleClassIntToBool { + final Map<int, bool> value; + + @JsonKey(nullable: false) + final Map<int, bool> nullable; + + SimpleClassIntToBool( + this.value, + this.nullable, + ); + + factory SimpleClassIntToBool.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntToBoolFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToBoolToJson(this); +} + +@JsonSerializable() +class SimpleClassObjectToBool { + final Map<Object, bool> value; + + @JsonKey(nullable: false) + final Map<Object, bool> nullable; + + SimpleClassObjectToBool( + this.value, + this.nullable, + ); + + factory SimpleClassObjectToBool.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectToBoolFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToBoolToJson(this); +} + +@JsonSerializable() +class SimpleClassStringToBool { + final Map<String, bool> value; + + @JsonKey(nullable: false) + final Map<String, bool> nullable; + + SimpleClassStringToBool( + this.value, + this.nullable, + ); + + factory SimpleClassStringToBool.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringToBoolFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToBoolToJson(this); +} + +@JsonSerializable() +class SimpleClassUriToBool { + final Map<Uri, bool> value; + + @JsonKey(nullable: false) + final Map<Uri, bool> nullable; + + SimpleClassUriToBool( + this.value, + this.nullable, + ); + + factory SimpleClassUriToBool.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriToBoolFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToBoolToJson(this); +} + +@JsonSerializable() +class SimpleClassBigIntToDateTime { + final Map<BigInt, DateTime> value; + + @JsonKey(nullable: false) + final Map<BigInt, DateTime> nullable; + + SimpleClassBigIntToDateTime( + this.value, + this.nullable, + ); + + factory SimpleClassBigIntToDateTime.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntToDateTimeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToDateTimeToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTimeToDateTime { + final Map<DateTime, DateTime> value; + + @JsonKey(nullable: false) + final Map<DateTime, DateTime> nullable; + + SimpleClassDateTimeToDateTime( + this.value, + this.nullable, + ); + + factory SimpleClassDateTimeToDateTime.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeToDateTimeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToDateTimeToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamicToDateTime { + final Map<dynamic, DateTime> value; + + @JsonKey(nullable: false) + final Map<dynamic, DateTime> nullable; + + SimpleClassDynamicToDateTime( + this.value, + this.nullable, + ); + + factory SimpleClassDynamicToDateTime.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicToDateTimeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToDateTimeToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumTypeToDateTime { + final Map<EnumType, DateTime> value; + + @JsonKey(nullable: false) + final Map<EnumType, DateTime> nullable; + + SimpleClassEnumTypeToDateTime( + this.value, + this.nullable, + ); + + factory SimpleClassEnumTypeToDateTime.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeToDateTimeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToDateTimeToJson(this); +} + +@JsonSerializable() +class SimpleClassIntToDateTime { + final Map<int, DateTime> value; + + @JsonKey(nullable: false) + final Map<int, DateTime> nullable; + + SimpleClassIntToDateTime( + this.value, + this.nullable, + ); + + factory SimpleClassIntToDateTime.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntToDateTimeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToDateTimeToJson(this); +} + +@JsonSerializable() +class SimpleClassObjectToDateTime { + final Map<Object, DateTime> value; + + @JsonKey(nullable: false) + final Map<Object, DateTime> nullable; + + SimpleClassObjectToDateTime( + this.value, + this.nullable, + ); + + factory SimpleClassObjectToDateTime.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectToDateTimeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToDateTimeToJson(this); +} + +@JsonSerializable() +class SimpleClassStringToDateTime { + final Map<String, DateTime> value; + + @JsonKey(nullable: false) + final Map<String, DateTime> nullable; + + SimpleClassStringToDateTime( + this.value, + this.nullable, + ); + + factory SimpleClassStringToDateTime.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringToDateTimeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToDateTimeToJson(this); +} + +@JsonSerializable() +class SimpleClassUriToDateTime { + final Map<Uri, DateTime> value; + + @JsonKey(nullable: false) + final Map<Uri, DateTime> nullable; + + SimpleClassUriToDateTime( + this.value, + this.nullable, + ); + + factory SimpleClassUriToDateTime.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriToDateTimeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToDateTimeToJson(this); +} + +@JsonSerializable() +class SimpleClassBigIntToDouble { + final Map<BigInt, double> value; + + @JsonKey(nullable: false) + final Map<BigInt, double> nullable; + + SimpleClassBigIntToDouble( + this.value, + this.nullable, + ); + + factory SimpleClassBigIntToDouble.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntToDoubleFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToDoubleToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTimeToDouble { + final Map<DateTime, double> value; + + @JsonKey(nullable: false) + final Map<DateTime, double> nullable; + + SimpleClassDateTimeToDouble( + this.value, + this.nullable, + ); + + factory SimpleClassDateTimeToDouble.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeToDoubleFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToDoubleToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamicToDouble { + final Map<dynamic, double> value; + + @JsonKey(nullable: false) + final Map<dynamic, double> nullable; + + SimpleClassDynamicToDouble( + this.value, + this.nullable, + ); + + factory SimpleClassDynamicToDouble.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicToDoubleFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToDoubleToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumTypeToDouble { + final Map<EnumType, double> value; + + @JsonKey(nullable: false) + final Map<EnumType, double> nullable; + + SimpleClassEnumTypeToDouble( + this.value, + this.nullable, + ); + + factory SimpleClassEnumTypeToDouble.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeToDoubleFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToDoubleToJson(this); +} + +@JsonSerializable() +class SimpleClassIntToDouble { + final Map<int, double> value; + + @JsonKey(nullable: false) + final Map<int, double> nullable; + + SimpleClassIntToDouble( + this.value, + this.nullable, + ); + + factory SimpleClassIntToDouble.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntToDoubleFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToDoubleToJson(this); +} + +@JsonSerializable() +class SimpleClassObjectToDouble { + final Map<Object, double> value; + + @JsonKey(nullable: false) + final Map<Object, double> nullable; + + SimpleClassObjectToDouble( + this.value, + this.nullable, + ); + + factory SimpleClassObjectToDouble.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectToDoubleFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToDoubleToJson(this); +} + +@JsonSerializable() +class SimpleClassStringToDouble { + final Map<String, double> value; + + @JsonKey(nullable: false) + final Map<String, double> nullable; + + SimpleClassStringToDouble( + this.value, + this.nullable, + ); + + factory SimpleClassStringToDouble.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringToDoubleFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToDoubleToJson(this); +} + +@JsonSerializable() +class SimpleClassUriToDouble { + final Map<Uri, double> value; + + @JsonKey(nullable: false) + final Map<Uri, double> nullable; + + SimpleClassUriToDouble( + this.value, + this.nullable, + ); + + factory SimpleClassUriToDouble.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriToDoubleFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToDoubleToJson(this); +} + +@JsonSerializable() +class SimpleClassBigIntToDuration { + final Map<BigInt, Duration> value; + + @JsonKey(nullable: false) + final Map<BigInt, Duration> nullable; + + SimpleClassBigIntToDuration( + this.value, + this.nullable, + ); + + factory SimpleClassBigIntToDuration.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntToDurationFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToDurationToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTimeToDuration { + final Map<DateTime, Duration> value; + + @JsonKey(nullable: false) + final Map<DateTime, Duration> nullable; + + SimpleClassDateTimeToDuration( + this.value, + this.nullable, + ); + + factory SimpleClassDateTimeToDuration.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeToDurationFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToDurationToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamicToDuration { + final Map<dynamic, Duration> value; + + @JsonKey(nullable: false) + final Map<dynamic, Duration> nullable; + + SimpleClassDynamicToDuration( + this.value, + this.nullable, + ); + + factory SimpleClassDynamicToDuration.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicToDurationFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToDurationToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumTypeToDuration { + final Map<EnumType, Duration> value; + + @JsonKey(nullable: false) + final Map<EnumType, Duration> nullable; + + SimpleClassEnumTypeToDuration( + this.value, + this.nullable, + ); + + factory SimpleClassEnumTypeToDuration.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeToDurationFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToDurationToJson(this); +} + +@JsonSerializable() +class SimpleClassIntToDuration { + final Map<int, Duration> value; + + @JsonKey(nullable: false) + final Map<int, Duration> nullable; + + SimpleClassIntToDuration( + this.value, + this.nullable, + ); + + factory SimpleClassIntToDuration.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntToDurationFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToDurationToJson(this); +} + +@JsonSerializable() +class SimpleClassObjectToDuration { + final Map<Object, Duration> value; + + @JsonKey(nullable: false) + final Map<Object, Duration> nullable; + + SimpleClassObjectToDuration( + this.value, + this.nullable, + ); + + factory SimpleClassObjectToDuration.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectToDurationFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToDurationToJson(this); +} + +@JsonSerializable() +class SimpleClassStringToDuration { + final Map<String, Duration> value; + + @JsonKey(nullable: false) + final Map<String, Duration> nullable; + + SimpleClassStringToDuration( + this.value, + this.nullable, + ); + + factory SimpleClassStringToDuration.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringToDurationFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToDurationToJson(this); +} + +@JsonSerializable() +class SimpleClassUriToDuration { + final Map<Uri, Duration> value; + + @JsonKey(nullable: false) + final Map<Uri, Duration> nullable; + + SimpleClassUriToDuration( + this.value, + this.nullable, + ); + + factory SimpleClassUriToDuration.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriToDurationFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToDurationToJson(this); +} + +@JsonSerializable() +class SimpleClassBigIntToDynamic { + final Map<BigInt, dynamic> value; + + @JsonKey(nullable: false) + final Map<BigInt, dynamic> nullable; + + SimpleClassBigIntToDynamic( + this.value, + this.nullable, + ); + + factory SimpleClassBigIntToDynamic.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntToDynamicFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToDynamicToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTimeToDynamic { + final Map<DateTime, dynamic> value; + + @JsonKey(nullable: false) + final Map<DateTime, dynamic> nullable; + + SimpleClassDateTimeToDynamic( + this.value, + this.nullable, + ); + + factory SimpleClassDateTimeToDynamic.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeToDynamicFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToDynamicToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamicToDynamic { + final Map<dynamic, dynamic> value; + + @JsonKey(nullable: false) + final Map<dynamic, dynamic> nullable; + + SimpleClassDynamicToDynamic( + this.value, + this.nullable, + ); + + factory SimpleClassDynamicToDynamic.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicToDynamicFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToDynamicToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumTypeToDynamic { + final Map<EnumType, dynamic> value; + + @JsonKey(nullable: false) + final Map<EnumType, dynamic> nullable; + + SimpleClassEnumTypeToDynamic( + this.value, + this.nullable, + ); + + factory SimpleClassEnumTypeToDynamic.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeToDynamicFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToDynamicToJson(this); +} + +@JsonSerializable() +class SimpleClassIntToDynamic { + final Map<int, dynamic> value; + + @JsonKey(nullable: false) + final Map<int, dynamic> nullable; + + SimpleClassIntToDynamic( + this.value, + this.nullable, + ); + + factory SimpleClassIntToDynamic.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntToDynamicFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToDynamicToJson(this); +} + +@JsonSerializable() +class SimpleClassObjectToDynamic { + final Map<Object, dynamic> value; + + @JsonKey(nullable: false) + final Map<Object, dynamic> nullable; + + SimpleClassObjectToDynamic( + this.value, + this.nullable, + ); + + factory SimpleClassObjectToDynamic.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectToDynamicFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToDynamicToJson(this); +} + +@JsonSerializable() +class SimpleClassStringToDynamic { + final Map<String, dynamic> value; + + @JsonKey(nullable: false) + final Map<String, dynamic> nullable; + + SimpleClassStringToDynamic( + this.value, + this.nullable, + ); + + factory SimpleClassStringToDynamic.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringToDynamicFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToDynamicToJson(this); +} + +@JsonSerializable() +class SimpleClassUriToDynamic { + final Map<Uri, dynamic> value; + + @JsonKey(nullable: false) + final Map<Uri, dynamic> nullable; + + SimpleClassUriToDynamic( + this.value, + this.nullable, + ); + + factory SimpleClassUriToDynamic.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriToDynamicFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToDynamicToJson(this); +} + +@JsonSerializable() +class SimpleClassBigIntToEnumType { + final Map<BigInt, EnumType> value; + + @JsonKey(nullable: false) + final Map<BigInt, EnumType> nullable; + + SimpleClassBigIntToEnumType( + this.value, + this.nullable, + ); + + factory SimpleClassBigIntToEnumType.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntToEnumTypeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToEnumTypeToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTimeToEnumType { + final Map<DateTime, EnumType> value; + + @JsonKey(nullable: false) + final Map<DateTime, EnumType> nullable; + + SimpleClassDateTimeToEnumType( + this.value, + this.nullable, + ); + + factory SimpleClassDateTimeToEnumType.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeToEnumTypeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToEnumTypeToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamicToEnumType { + final Map<dynamic, EnumType> value; + + @JsonKey(nullable: false) + final Map<dynamic, EnumType> nullable; + + SimpleClassDynamicToEnumType( + this.value, + this.nullable, + ); + + factory SimpleClassDynamicToEnumType.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicToEnumTypeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToEnumTypeToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumTypeToEnumType { + final Map<EnumType, EnumType> value; + + @JsonKey(nullable: false) + final Map<EnumType, EnumType> nullable; + + SimpleClassEnumTypeToEnumType( + this.value, + this.nullable, + ); + + factory SimpleClassEnumTypeToEnumType.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeToEnumTypeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToEnumTypeToJson(this); +} + +@JsonSerializable() +class SimpleClassIntToEnumType { + final Map<int, EnumType> value; + + @JsonKey(nullable: false) + final Map<int, EnumType> nullable; + + SimpleClassIntToEnumType( + this.value, + this.nullable, + ); + + factory SimpleClassIntToEnumType.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntToEnumTypeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToEnumTypeToJson(this); +} + +@JsonSerializable() +class SimpleClassObjectToEnumType { + final Map<Object, EnumType> value; + + @JsonKey(nullable: false) + final Map<Object, EnumType> nullable; + + SimpleClassObjectToEnumType( + this.value, + this.nullable, + ); + + factory SimpleClassObjectToEnumType.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectToEnumTypeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToEnumTypeToJson(this); +} + +@JsonSerializable() +class SimpleClassStringToEnumType { + final Map<String, EnumType> value; + + @JsonKey(nullable: false) + final Map<String, EnumType> nullable; + + SimpleClassStringToEnumType( + this.value, + this.nullable, + ); + + factory SimpleClassStringToEnumType.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringToEnumTypeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToEnumTypeToJson(this); +} + +@JsonSerializable() +class SimpleClassUriToEnumType { + final Map<Uri, EnumType> value; + + @JsonKey(nullable: false) + final Map<Uri, EnumType> nullable; + + SimpleClassUriToEnumType( + this.value, + this.nullable, + ); + + factory SimpleClassUriToEnumType.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriToEnumTypeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToEnumTypeToJson(this); +} + +@JsonSerializable() +class SimpleClassBigIntToInt { + final Map<BigInt, int> value; + + @JsonKey(nullable: false) + final Map<BigInt, int> nullable; + + SimpleClassBigIntToInt( + this.value, + this.nullable, + ); + + factory SimpleClassBigIntToInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntToIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToIntToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTimeToInt { + final Map<DateTime, int> value; + + @JsonKey(nullable: false) + final Map<DateTime, int> nullable; + + SimpleClassDateTimeToInt( + this.value, + this.nullable, + ); + + factory SimpleClassDateTimeToInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeToIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToIntToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamicToInt { + final Map<dynamic, int> value; + + @JsonKey(nullable: false) + final Map<dynamic, int> nullable; + + SimpleClassDynamicToInt( + this.value, + this.nullable, + ); + + factory SimpleClassDynamicToInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicToIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToIntToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumTypeToInt { + final Map<EnumType, int> value; + + @JsonKey(nullable: false) + final Map<EnumType, int> nullable; + + SimpleClassEnumTypeToInt( + this.value, + this.nullable, + ); + + factory SimpleClassEnumTypeToInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeToIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToIntToJson(this); +} + +@JsonSerializable() +class SimpleClassIntToInt { + final Map<int, int> value; + + @JsonKey(nullable: false) + final Map<int, int> nullable; + + SimpleClassIntToInt( + this.value, + this.nullable, + ); + + factory SimpleClassIntToInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntToIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToIntToJson(this); +} + +@JsonSerializable() +class SimpleClassObjectToInt { + final Map<Object, int> value; + + @JsonKey(nullable: false) + final Map<Object, int> nullable; + + SimpleClassObjectToInt( + this.value, + this.nullable, + ); + + factory SimpleClassObjectToInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectToIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToIntToJson(this); +} + +@JsonSerializable() +class SimpleClassStringToInt { + final Map<String, int> value; + + @JsonKey(nullable: false) + final Map<String, int> nullable; + + SimpleClassStringToInt( + this.value, + this.nullable, + ); + + factory SimpleClassStringToInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringToIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToIntToJson(this); +} + +@JsonSerializable() +class SimpleClassUriToInt { + final Map<Uri, int> value; + + @JsonKey(nullable: false) + final Map<Uri, int> nullable; + + SimpleClassUriToInt( + this.value, + this.nullable, + ); + + factory SimpleClassUriToInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriToIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToIntToJson(this); +} + +@JsonSerializable() +class SimpleClassBigIntToNum { + final Map<BigInt, num> value; + + @JsonKey(nullable: false) + final Map<BigInt, num> nullable; + + SimpleClassBigIntToNum( + this.value, + this.nullable, + ); + + factory SimpleClassBigIntToNum.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntToNumFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToNumToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTimeToNum { + final Map<DateTime, num> value; + + @JsonKey(nullable: false) + final Map<DateTime, num> nullable; + + SimpleClassDateTimeToNum( + this.value, + this.nullable, + ); + + factory SimpleClassDateTimeToNum.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeToNumFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToNumToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamicToNum { + final Map<dynamic, num> value; + + @JsonKey(nullable: false) + final Map<dynamic, num> nullable; + + SimpleClassDynamicToNum( + this.value, + this.nullable, + ); + + factory SimpleClassDynamicToNum.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicToNumFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToNumToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumTypeToNum { + final Map<EnumType, num> value; + + @JsonKey(nullable: false) + final Map<EnumType, num> nullable; + + SimpleClassEnumTypeToNum( + this.value, + this.nullable, + ); + + factory SimpleClassEnumTypeToNum.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeToNumFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToNumToJson(this); +} + +@JsonSerializable() +class SimpleClassIntToNum { + final Map<int, num> value; + + @JsonKey(nullable: false) + final Map<int, num> nullable; + + SimpleClassIntToNum( + this.value, + this.nullable, + ); + + factory SimpleClassIntToNum.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntToNumFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToNumToJson(this); +} + +@JsonSerializable() +class SimpleClassObjectToNum { + final Map<Object, num> value; + + @JsonKey(nullable: false) + final Map<Object, num> nullable; + + SimpleClassObjectToNum( + this.value, + this.nullable, + ); + + factory SimpleClassObjectToNum.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectToNumFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToNumToJson(this); +} + +@JsonSerializable() +class SimpleClassStringToNum { + final Map<String, num> value; + + @JsonKey(nullable: false) + final Map<String, num> nullable; + + SimpleClassStringToNum( + this.value, + this.nullable, + ); + + factory SimpleClassStringToNum.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringToNumFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToNumToJson(this); +} + +@JsonSerializable() +class SimpleClassUriToNum { + final Map<Uri, num> value; + + @JsonKey(nullable: false) + final Map<Uri, num> nullable; + + SimpleClassUriToNum( + this.value, + this.nullable, + ); + + factory SimpleClassUriToNum.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriToNumFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToNumToJson(this); +} + +@JsonSerializable() +class SimpleClassBigIntToObject { + final Map<BigInt, Object> value; + + @JsonKey(nullable: false) + final Map<BigInt, Object> nullable; + + SimpleClassBigIntToObject( + this.value, + this.nullable, + ); + + factory SimpleClassBigIntToObject.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntToObjectFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToObjectToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTimeToObject { + final Map<DateTime, Object> value; + + @JsonKey(nullable: false) + final Map<DateTime, Object> nullable; + + SimpleClassDateTimeToObject( + this.value, + this.nullable, + ); + + factory SimpleClassDateTimeToObject.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeToObjectFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToObjectToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamicToObject { + final Map<dynamic, Object> value; + + @JsonKey(nullable: false) + final Map<dynamic, Object> nullable; + + SimpleClassDynamicToObject( + this.value, + this.nullable, + ); + + factory SimpleClassDynamicToObject.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicToObjectFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToObjectToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumTypeToObject { + final Map<EnumType, Object> value; + + @JsonKey(nullable: false) + final Map<EnumType, Object> nullable; + + SimpleClassEnumTypeToObject( + this.value, + this.nullable, + ); + + factory SimpleClassEnumTypeToObject.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeToObjectFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToObjectToJson(this); +} + +@JsonSerializable() +class SimpleClassIntToObject { + final Map<int, Object> value; + + @JsonKey(nullable: false) + final Map<int, Object> nullable; + + SimpleClassIntToObject( + this.value, + this.nullable, + ); + + factory SimpleClassIntToObject.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntToObjectFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToObjectToJson(this); +} + +@JsonSerializable() +class SimpleClassObjectToObject { + final Map<Object, Object> value; + + @JsonKey(nullable: false) + final Map<Object, Object> nullable; + + SimpleClassObjectToObject( + this.value, + this.nullable, + ); + + factory SimpleClassObjectToObject.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectToObjectFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToObjectToJson(this); +} + +@JsonSerializable() +class SimpleClassStringToObject { + final Map<String, Object> value; + + @JsonKey(nullable: false) + final Map<String, Object> nullable; + + SimpleClassStringToObject( + this.value, + this.nullable, + ); + + factory SimpleClassStringToObject.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringToObjectFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToObjectToJson(this); +} + +@JsonSerializable() +class SimpleClassUriToObject { + final Map<Uri, Object> value; + + @JsonKey(nullable: false) + final Map<Uri, Object> nullable; + + SimpleClassUriToObject( + this.value, + this.nullable, + ); + + factory SimpleClassUriToObject.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriToObjectFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToObjectToJson(this); +} + +@JsonSerializable() +class SimpleClassBigIntToString { + final Map<BigInt, String> value; + + @JsonKey(nullable: false) + final Map<BigInt, String> nullable; + + SimpleClassBigIntToString( + this.value, + this.nullable, + ); + + factory SimpleClassBigIntToString.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntToStringFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToStringToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTimeToString { + final Map<DateTime, String> value; + + @JsonKey(nullable: false) + final Map<DateTime, String> nullable; + + SimpleClassDateTimeToString( + this.value, + this.nullable, + ); + + factory SimpleClassDateTimeToString.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeToStringFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToStringToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamicToString { + final Map<dynamic, String> value; + + @JsonKey(nullable: false) + final Map<dynamic, String> nullable; + + SimpleClassDynamicToString( + this.value, + this.nullable, + ); + + factory SimpleClassDynamicToString.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicToStringFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToStringToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumTypeToString { + final Map<EnumType, String> value; + + @JsonKey(nullable: false) + final Map<EnumType, String> nullable; + + SimpleClassEnumTypeToString( + this.value, + this.nullable, + ); + + factory SimpleClassEnumTypeToString.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeToStringFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToStringToJson(this); +} + +@JsonSerializable() +class SimpleClassIntToString { + final Map<int, String> value; + + @JsonKey(nullable: false) + final Map<int, String> nullable; + + SimpleClassIntToString( + this.value, + this.nullable, + ); + + factory SimpleClassIntToString.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntToStringFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToStringToJson(this); +} + +@JsonSerializable() +class SimpleClassObjectToString { + final Map<Object, String> value; + + @JsonKey(nullable: false) + final Map<Object, String> nullable; + + SimpleClassObjectToString( + this.value, + this.nullable, + ); + + factory SimpleClassObjectToString.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectToStringFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToStringToJson(this); +} + +@JsonSerializable() +class SimpleClassStringToString { + final Map<String, String> value; + + @JsonKey(nullable: false) + final Map<String, String> nullable; + + SimpleClassStringToString( + this.value, + this.nullable, + ); + + factory SimpleClassStringToString.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringToStringFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToStringToJson(this); +} + +@JsonSerializable() +class SimpleClassUriToString { + final Map<Uri, String> value; + + @JsonKey(nullable: false) + final Map<Uri, String> nullable; + + SimpleClassUriToString( + this.value, + this.nullable, + ); + + factory SimpleClassUriToString.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriToStringFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToStringToJson(this); +} + +@JsonSerializable() +class SimpleClassBigIntToUri { + final Map<BigInt, Uri> value; + + @JsonKey(nullable: false) + final Map<BigInt, Uri> nullable; + + SimpleClassBigIntToUri( + this.value, + this.nullable, + ); + + factory SimpleClassBigIntToUri.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntToUriFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToUriToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTimeToUri { + final Map<DateTime, Uri> value; + + @JsonKey(nullable: false) + final Map<DateTime, Uri> nullable; + + SimpleClassDateTimeToUri( + this.value, + this.nullable, + ); + + factory SimpleClassDateTimeToUri.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeToUriFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToUriToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamicToUri { + final Map<dynamic, Uri> value; + + @JsonKey(nullable: false) + final Map<dynamic, Uri> nullable; + + SimpleClassDynamicToUri( + this.value, + this.nullable, + ); + + factory SimpleClassDynamicToUri.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicToUriFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToUriToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumTypeToUri { + final Map<EnumType, Uri> value; + + @JsonKey(nullable: false) + final Map<EnumType, Uri> nullable; + + SimpleClassEnumTypeToUri( + this.value, + this.nullable, + ); + + factory SimpleClassEnumTypeToUri.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeToUriFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToUriToJson(this); +} + +@JsonSerializable() +class SimpleClassIntToUri { + final Map<int, Uri> value; + + @JsonKey(nullable: false) + final Map<int, Uri> nullable; + + SimpleClassIntToUri( + this.value, + this.nullable, + ); + + factory SimpleClassIntToUri.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntToUriFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToUriToJson(this); +} + +@JsonSerializable() +class SimpleClassObjectToUri { + final Map<Object, Uri> value; + + @JsonKey(nullable: false) + final Map<Object, Uri> nullable; + + SimpleClassObjectToUri( + this.value, + this.nullable, + ); + + factory SimpleClassObjectToUri.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectToUriFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToUriToJson(this); +} + +@JsonSerializable() +class SimpleClassStringToUri { + final Map<String, Uri> value; + + @JsonKey(nullable: false) + final Map<String, Uri> nullable; + + SimpleClassStringToUri( + this.value, + this.nullable, + ); + + factory SimpleClassStringToUri.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringToUriFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToUriToJson(this); +} + +@JsonSerializable() +class SimpleClassUriToUri { + final Map<Uri, Uri> value; + + @JsonKey(nullable: false) + final Map<Uri, Uri> nullable; + + SimpleClassUriToUri( + this.value, + this.nullable, + ); + + factory SimpleClassUriToUri.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriToUriFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToUriToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_map.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_map.g.dart new file mode 100644 index 000000000..d1817bc25 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_map.g.dart @@ -0,0 +1,1931 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_map.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'] as Map<String, dynamic>, + json['nullable'] as Map<String, dynamic>, + )..withDefault = json['withDefault'] as Map<String, dynamic> ?? {'a': 1}; +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + 'withDefault': instance.withDefault, + }; + +SimpleClassBigIntToBigInt _$SimpleClassBigIntToBigIntFromJson( + Map<String, dynamic> json) { + return SimpleClassBigIntToBigInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry( + BigInt.parse(k), e == null ? null : BigInt.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(BigInt.parse(k), BigInt.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToBigIntToJson( + SimpleClassBigIntToBigInt instance) => + <String, dynamic>{ + 'value': + instance.value?.map((k, e) => MapEntry(k.toString(), e?.toString())), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toString(), e.toString())), + }; + +SimpleClassDateTimeToBigInt _$SimpleClassDateTimeToBigIntFromJson( + Map<String, dynamic> json) { + return SimpleClassDateTimeToBigInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry( + DateTime.parse(k), e == null ? null : BigInt.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(DateTime.parse(k), BigInt.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToBigIntToJson( + SimpleClassDateTimeToBigInt instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toIso8601String(), e?.toString())), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toIso8601String(), e.toString())), + }; + +SimpleClassDynamicToBigInt _$SimpleClassDynamicToBigIntFromJson( + Map<String, dynamic> json) { + return SimpleClassDynamicToBigInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e == null ? null : BigInt.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, BigInt.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToBigIntToJson( + SimpleClassDynamicToBigInt instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, e?.toString())), + 'nullable': instance.nullable.map((k, e) => MapEntry(k, e.toString())), + }; + +SimpleClassEnumTypeToBigInt _$SimpleClassEnumTypeToBigIntFromJson( + Map<String, dynamic> json) { + return SimpleClassEnumTypeToBigInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(_$enumDecodeNullable(_$EnumTypeEnumMap, k), + e == null ? null : BigInt.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry( + _$enumDecode(_$EnumTypeEnumMap, k), BigInt.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToBigIntToJson( + SimpleClassEnumTypeToBigInt instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e?.toString())), + 'nullable': instance.nullable + .map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e.toString())), + }; + +T _$enumDecode<T>( + Map<T, dynamic> enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} + +T _$enumDecodeNullable<T>( + Map<T, dynamic> enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode<T>(enumValues, source, unknownValue: unknownValue); +} + +const _$EnumTypeEnumMap = { + EnumType.alpha: 'alpha', + EnumType.beta: 'beta', + EnumType.gamma: 'gamma', + EnumType.delta: 'delta', +}; + +SimpleClassIntToBigInt _$SimpleClassIntToBigIntFromJson( + Map<String, dynamic> json) { + return SimpleClassIntToBigInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => + MapEntry(int.parse(k), e == null ? null : BigInt.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(int.parse(k), BigInt.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassIntToBigIntToJson( + SimpleClassIntToBigInt instance) => + <String, dynamic>{ + 'value': + instance.value?.map((k, e) => MapEntry(k.toString(), e?.toString())), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toString(), e.toString())), + }; + +SimpleClassObjectToBigInt _$SimpleClassObjectToBigIntFromJson( + Map<String, dynamic> json) { + return SimpleClassObjectToBigInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e == null ? null : BigInt.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, BigInt.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassObjectToBigIntToJson( + SimpleClassObjectToBigInt instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, e?.toString())), + 'nullable': instance.nullable.map((k, e) => MapEntry(k, e.toString())), + }; + +SimpleClassStringToBigInt _$SimpleClassStringToBigIntFromJson( + Map<String, dynamic> json) { + return SimpleClassStringToBigInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e == null ? null : BigInt.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, BigInt.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassStringToBigIntToJson( + SimpleClassStringToBigInt instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, e?.toString())), + 'nullable': instance.nullable.map((k, e) => MapEntry(k, e.toString())), + }; + +SimpleClassUriToBigInt _$SimpleClassUriToBigIntFromJson( + Map<String, dynamic> json) { + return SimpleClassUriToBigInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => + MapEntry(Uri.parse(k), e == null ? null : BigInt.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(Uri.parse(k), BigInt.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassUriToBigIntToJson( + SimpleClassUriToBigInt instance) => + <String, dynamic>{ + 'value': + instance.value?.map((k, e) => MapEntry(k.toString(), e?.toString())), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toString(), e.toString())), + }; + +SimpleClassBigIntToBool _$SimpleClassBigIntToBoolFromJson( + Map<String, dynamic> json) { + return SimpleClassBigIntToBool( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(BigInt.parse(k), e as bool), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(BigInt.parse(k), e as bool), + ), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToBoolToJson( + SimpleClassBigIntToBool instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassDateTimeToBool _$SimpleClassDateTimeToBoolFromJson( + Map<String, dynamic> json) { + return SimpleClassDateTimeToBool( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(DateTime.parse(k), e as bool), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(DateTime.parse(k), e as bool), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToBoolToJson( + SimpleClassDateTimeToBool instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toIso8601String(), e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toIso8601String(), e)), + }; + +SimpleClassDynamicToBool _$SimpleClassDynamicToBoolFromJson( + Map<String, dynamic> json) { + return SimpleClassDynamicToBool( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e as bool), + ), + Map<String, bool>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToBoolToJson( + SimpleClassDynamicToBool instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassEnumTypeToBool _$SimpleClassEnumTypeToBoolFromJson( + Map<String, dynamic> json) { + return SimpleClassEnumTypeToBool( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(_$enumDecodeNullable(_$EnumTypeEnumMap, k), e as bool), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(_$enumDecode(_$EnumTypeEnumMap, k), e as bool), + ), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToBoolToJson( + SimpleClassEnumTypeToBool instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + }; + +SimpleClassIntToBool _$SimpleClassIntToBoolFromJson(Map<String, dynamic> json) { + return SimpleClassIntToBool( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(int.parse(k), e as bool), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(int.parse(k), e as bool), + ), + ); +} + +Map<String, dynamic> _$SimpleClassIntToBoolToJson( + SimpleClassIntToBool instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassObjectToBool _$SimpleClassObjectToBoolFromJson( + Map<String, dynamic> json) { + return SimpleClassObjectToBool( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e as bool), + ), + Map<String, bool>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassObjectToBoolToJson( + SimpleClassObjectToBool instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassStringToBool _$SimpleClassStringToBoolFromJson( + Map<String, dynamic> json) { + return SimpleClassStringToBool( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e as bool), + ), + Map<String, bool>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassStringToBoolToJson( + SimpleClassStringToBool instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassUriToBool _$SimpleClassUriToBoolFromJson(Map<String, dynamic> json) { + return SimpleClassUriToBool( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(Uri.parse(k), e as bool), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(Uri.parse(k), e as bool), + ), + ); +} + +Map<String, dynamic> _$SimpleClassUriToBoolToJson( + SimpleClassUriToBool instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassBigIntToDateTime _$SimpleClassBigIntToDateTimeFromJson( + Map<String, dynamic> json) { + return SimpleClassBigIntToDateTime( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry( + BigInt.parse(k), e == null ? null : DateTime.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(BigInt.parse(k), DateTime.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToDateTimeToJson( + SimpleClassBigIntToDateTime instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toString(), e?.toIso8601String())), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toString(), e.toIso8601String())), + }; + +SimpleClassDateTimeToDateTime _$SimpleClassDateTimeToDateTimeFromJson( + Map<String, dynamic> json) { + return SimpleClassDateTimeToDateTime( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry( + DateTime.parse(k), e == null ? null : DateTime.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(DateTime.parse(k), DateTime.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToDateTimeToJson( + SimpleClassDateTimeToDateTime instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toIso8601String(), e?.toIso8601String())), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toIso8601String(), e.toIso8601String())), + }; + +SimpleClassDynamicToDateTime _$SimpleClassDynamicToDateTimeFromJson( + Map<String, dynamic> json) { + return SimpleClassDynamicToDateTime( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e == null ? null : DateTime.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, DateTime.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToDateTimeToJson( + SimpleClassDynamicToDateTime instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, e?.toIso8601String())), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k, e.toIso8601String())), + }; + +SimpleClassEnumTypeToDateTime _$SimpleClassEnumTypeToDateTimeFromJson( + Map<String, dynamic> json) { + return SimpleClassEnumTypeToDateTime( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(_$enumDecodeNullable(_$EnumTypeEnumMap, k), + e == null ? null : DateTime.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry( + _$enumDecode(_$EnumTypeEnumMap, k), DateTime.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToDateTimeToJson( + SimpleClassEnumTypeToDateTime instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e?.toIso8601String())), + 'nullable': instance.nullable + .map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e.toIso8601String())), + }; + +SimpleClassIntToDateTime _$SimpleClassIntToDateTimeFromJson( + Map<String, dynamic> json) { + return SimpleClassIntToDateTime( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry( + int.parse(k), e == null ? null : DateTime.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(int.parse(k), DateTime.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassIntToDateTimeToJson( + SimpleClassIntToDateTime instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toString(), e?.toIso8601String())), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toString(), e.toIso8601String())), + }; + +SimpleClassObjectToDateTime _$SimpleClassObjectToDateTimeFromJson( + Map<String, dynamic> json) { + return SimpleClassObjectToDateTime( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e == null ? null : DateTime.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, DateTime.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassObjectToDateTimeToJson( + SimpleClassObjectToDateTime instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, e?.toIso8601String())), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k, e.toIso8601String())), + }; + +SimpleClassStringToDateTime _$SimpleClassStringToDateTimeFromJson( + Map<String, dynamic> json) { + return SimpleClassStringToDateTime( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e == null ? null : DateTime.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, DateTime.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassStringToDateTimeToJson( + SimpleClassStringToDateTime instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, e?.toIso8601String())), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k, e.toIso8601String())), + }; + +SimpleClassUriToDateTime _$SimpleClassUriToDateTimeFromJson( + Map<String, dynamic> json) { + return SimpleClassUriToDateTime( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry( + Uri.parse(k), e == null ? null : DateTime.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(Uri.parse(k), DateTime.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassUriToDateTimeToJson( + SimpleClassUriToDateTime instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toString(), e?.toIso8601String())), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toString(), e.toIso8601String())), + }; + +SimpleClassBigIntToDouble _$SimpleClassBigIntToDoubleFromJson( + Map<String, dynamic> json) { + return SimpleClassBigIntToDouble( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(BigInt.parse(k), (e as num)?.toDouble()), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(BigInt.parse(k), (e as num).toDouble()), + ), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToDoubleToJson( + SimpleClassBigIntToDouble instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassDateTimeToDouble _$SimpleClassDateTimeToDoubleFromJson( + Map<String, dynamic> json) { + return SimpleClassDateTimeToDouble( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(DateTime.parse(k), (e as num)?.toDouble()), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(DateTime.parse(k), (e as num).toDouble()), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToDoubleToJson( + SimpleClassDateTimeToDouble instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toIso8601String(), e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toIso8601String(), e)), + }; + +SimpleClassDynamicToDouble _$SimpleClassDynamicToDoubleFromJson( + Map<String, dynamic> json) { + return SimpleClassDynamicToDouble( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, (e as num)?.toDouble()), + ), + Map<String, double>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToDoubleToJson( + SimpleClassDynamicToDouble instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassEnumTypeToDouble _$SimpleClassEnumTypeToDoubleFromJson( + Map<String, dynamic> json) { + return SimpleClassEnumTypeToDouble( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry( + _$enumDecodeNullable(_$EnumTypeEnumMap, k), (e as num)?.toDouble()), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => + MapEntry(_$enumDecode(_$EnumTypeEnumMap, k), (e as num).toDouble()), + ), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToDoubleToJson( + SimpleClassEnumTypeToDouble instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + }; + +SimpleClassIntToDouble _$SimpleClassIntToDoubleFromJson( + Map<String, dynamic> json) { + return SimpleClassIntToDouble( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(int.parse(k), (e as num)?.toDouble()), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(int.parse(k), (e as num).toDouble()), + ), + ); +} + +Map<String, dynamic> _$SimpleClassIntToDoubleToJson( + SimpleClassIntToDouble instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassObjectToDouble _$SimpleClassObjectToDoubleFromJson( + Map<String, dynamic> json) { + return SimpleClassObjectToDouble( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, (e as num)?.toDouble()), + ), + Map<String, double>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassObjectToDoubleToJson( + SimpleClassObjectToDouble instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassStringToDouble _$SimpleClassStringToDoubleFromJson( + Map<String, dynamic> json) { + return SimpleClassStringToDouble( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, (e as num)?.toDouble()), + ), + Map<String, double>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassStringToDoubleToJson( + SimpleClassStringToDouble instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassUriToDouble _$SimpleClassUriToDoubleFromJson( + Map<String, dynamic> json) { + return SimpleClassUriToDouble( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(Uri.parse(k), (e as num)?.toDouble()), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(Uri.parse(k), (e as num).toDouble()), + ), + ); +} + +Map<String, dynamic> _$SimpleClassUriToDoubleToJson( + SimpleClassUriToDouble instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassBigIntToDuration _$SimpleClassBigIntToDurationFromJson( + Map<String, dynamic> json) { + return SimpleClassBigIntToDuration( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry( + BigInt.parse(k), e == null ? null : Duration(microseconds: e as int)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(BigInt.parse(k), Duration(microseconds: e as int)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToDurationToJson( + SimpleClassBigIntToDuration instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toString(), e?.inMicroseconds)), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toString(), e.inMicroseconds)), + }; + +SimpleClassDateTimeToDuration _$SimpleClassDateTimeToDurationFromJson( + Map<String, dynamic> json) { + return SimpleClassDateTimeToDuration( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(DateTime.parse(k), + e == null ? null : Duration(microseconds: e as int)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(DateTime.parse(k), Duration(microseconds: e as int)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToDurationToJson( + SimpleClassDateTimeToDuration instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toIso8601String(), e?.inMicroseconds)), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toIso8601String(), e.inMicroseconds)), + }; + +SimpleClassDynamicToDuration _$SimpleClassDynamicToDurationFromJson( + Map<String, dynamic> json) { + return SimpleClassDynamicToDuration( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => + MapEntry(k, e == null ? null : Duration(microseconds: e as int)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, Duration(microseconds: e as int)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToDurationToJson( + SimpleClassDynamicToDuration instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, e?.inMicroseconds)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k, e.inMicroseconds)), + }; + +SimpleClassEnumTypeToDuration _$SimpleClassEnumTypeToDurationFromJson( + Map<String, dynamic> json) { + return SimpleClassEnumTypeToDuration( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(_$enumDecodeNullable(_$EnumTypeEnumMap, k), + e == null ? null : Duration(microseconds: e as int)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry( + _$enumDecode(_$EnumTypeEnumMap, k), Duration(microseconds: e as int)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToDurationToJson( + SimpleClassEnumTypeToDuration instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e?.inMicroseconds)), + 'nullable': instance.nullable + .map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e.inMicroseconds)), + }; + +SimpleClassIntToDuration _$SimpleClassIntToDurationFromJson( + Map<String, dynamic> json) { + return SimpleClassIntToDuration( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry( + int.parse(k), e == null ? null : Duration(microseconds: e as int)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(int.parse(k), Duration(microseconds: e as int)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassIntToDurationToJson( + SimpleClassIntToDuration instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toString(), e?.inMicroseconds)), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toString(), e.inMicroseconds)), + }; + +SimpleClassObjectToDuration _$SimpleClassObjectToDurationFromJson( + Map<String, dynamic> json) { + return SimpleClassObjectToDuration( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => + MapEntry(k, e == null ? null : Duration(microseconds: e as int)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, Duration(microseconds: e as int)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassObjectToDurationToJson( + SimpleClassObjectToDuration instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, e?.inMicroseconds)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k, e.inMicroseconds)), + }; + +SimpleClassStringToDuration _$SimpleClassStringToDurationFromJson( + Map<String, dynamic> json) { + return SimpleClassStringToDuration( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => + MapEntry(k, e == null ? null : Duration(microseconds: e as int)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, Duration(microseconds: e as int)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassStringToDurationToJson( + SimpleClassStringToDuration instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, e?.inMicroseconds)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k, e.inMicroseconds)), + }; + +SimpleClassUriToDuration _$SimpleClassUriToDurationFromJson( + Map<String, dynamic> json) { + return SimpleClassUriToDuration( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry( + Uri.parse(k), e == null ? null : Duration(microseconds: e as int)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(Uri.parse(k), Duration(microseconds: e as int)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassUriToDurationToJson( + SimpleClassUriToDuration instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toString(), e?.inMicroseconds)), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toString(), e.inMicroseconds)), + }; + +SimpleClassBigIntToDynamic _$SimpleClassBigIntToDynamicFromJson( + Map<String, dynamic> json) { + return SimpleClassBigIntToDynamic( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(BigInt.parse(k), e), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(BigInt.parse(k), e), + ), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToDynamicToJson( + SimpleClassBigIntToDynamic instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassDateTimeToDynamic _$SimpleClassDateTimeToDynamicFromJson( + Map<String, dynamic> json) { + return SimpleClassDateTimeToDynamic( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(DateTime.parse(k), e), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(DateTime.parse(k), e), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToDynamicToJson( + SimpleClassDateTimeToDynamic instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toIso8601String(), e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toIso8601String(), e)), + }; + +SimpleClassDynamicToDynamic _$SimpleClassDynamicToDynamicFromJson( + Map<String, dynamic> json) { + return SimpleClassDynamicToDynamic( + json['value'] as Map<String, dynamic>, + json['nullable'] as Map<String, dynamic>, + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToDynamicToJson( + SimpleClassDynamicToDynamic instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassEnumTypeToDynamic _$SimpleClassEnumTypeToDynamicFromJson( + Map<String, dynamic> json) { + return SimpleClassEnumTypeToDynamic( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(_$enumDecodeNullable(_$EnumTypeEnumMap, k), e), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(_$enumDecode(_$EnumTypeEnumMap, k), e), + ), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToDynamicToJson( + SimpleClassEnumTypeToDynamic instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + }; + +SimpleClassIntToDynamic _$SimpleClassIntToDynamicFromJson( + Map<String, dynamic> json) { + return SimpleClassIntToDynamic( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(int.parse(k), e), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(int.parse(k), e), + ), + ); +} + +Map<String, dynamic> _$SimpleClassIntToDynamicToJson( + SimpleClassIntToDynamic instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassObjectToDynamic _$SimpleClassObjectToDynamicFromJson( + Map<String, dynamic> json) { + return SimpleClassObjectToDynamic( + json['value'] as Map<String, dynamic>, + json['nullable'] as Map<String, dynamic>, + ); +} + +Map<String, dynamic> _$SimpleClassObjectToDynamicToJson( + SimpleClassObjectToDynamic instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassStringToDynamic _$SimpleClassStringToDynamicFromJson( + Map<String, dynamic> json) { + return SimpleClassStringToDynamic( + json['value'] as Map<String, dynamic>, + json['nullable'] as Map<String, dynamic>, + ); +} + +Map<String, dynamic> _$SimpleClassStringToDynamicToJson( + SimpleClassStringToDynamic instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassUriToDynamic _$SimpleClassUriToDynamicFromJson( + Map<String, dynamic> json) { + return SimpleClassUriToDynamic( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(Uri.parse(k), e), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(Uri.parse(k), e), + ), + ); +} + +Map<String, dynamic> _$SimpleClassUriToDynamicToJson( + SimpleClassUriToDynamic instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassBigIntToEnumType _$SimpleClassBigIntToEnumTypeFromJson( + Map<String, dynamic> json) { + return SimpleClassBigIntToEnumType( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => + MapEntry(BigInt.parse(k), _$enumDecodeNullable(_$EnumTypeEnumMap, e)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(BigInt.parse(k), _$enumDecode(_$EnumTypeEnumMap, e)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToEnumTypeToJson( + SimpleClassBigIntToEnumType instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toString(), _$EnumTypeEnumMap[e])), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toString(), _$EnumTypeEnumMap[e])), + }; + +SimpleClassDateTimeToEnumType _$SimpleClassDateTimeToEnumTypeFromJson( + Map<String, dynamic> json) { + return SimpleClassDateTimeToEnumType( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry( + DateTime.parse(k), _$enumDecodeNullable(_$EnumTypeEnumMap, e)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(DateTime.parse(k), _$enumDecode(_$EnumTypeEnumMap, e)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToEnumTypeToJson( + SimpleClassDateTimeToEnumType instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toIso8601String(), _$EnumTypeEnumMap[e])), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toIso8601String(), _$EnumTypeEnumMap[e])), + }; + +SimpleClassDynamicToEnumType _$SimpleClassDynamicToEnumTypeFromJson( + Map<String, dynamic> json) { + return SimpleClassDynamicToEnumType( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, _$enumDecodeNullable(_$EnumTypeEnumMap, e)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, _$enumDecode(_$EnumTypeEnumMap, e)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToEnumTypeToJson( + SimpleClassDynamicToEnumType instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, _$EnumTypeEnumMap[e])), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k, _$EnumTypeEnumMap[e])), + }; + +SimpleClassEnumTypeToEnumType _$SimpleClassEnumTypeToEnumTypeFromJson( + Map<String, dynamic> json) { + return SimpleClassEnumTypeToEnumType( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(_$enumDecodeNullable(_$EnumTypeEnumMap, k), + _$enumDecodeNullable(_$EnumTypeEnumMap, e)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(_$enumDecode(_$EnumTypeEnumMap, k), + _$enumDecode(_$EnumTypeEnumMap, e)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToEnumTypeToJson( + SimpleClassEnumTypeToEnumType instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], _$EnumTypeEnumMap[e])), + 'nullable': instance.nullable + .map((k, e) => MapEntry(_$EnumTypeEnumMap[k], _$EnumTypeEnumMap[e])), + }; + +SimpleClassIntToEnumType _$SimpleClassIntToEnumTypeFromJson( + Map<String, dynamic> json) { + return SimpleClassIntToEnumType( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => + MapEntry(int.parse(k), _$enumDecodeNullable(_$EnumTypeEnumMap, e)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(int.parse(k), _$enumDecode(_$EnumTypeEnumMap, e)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassIntToEnumTypeToJson( + SimpleClassIntToEnumType instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toString(), _$EnumTypeEnumMap[e])), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toString(), _$EnumTypeEnumMap[e])), + }; + +SimpleClassObjectToEnumType _$SimpleClassObjectToEnumTypeFromJson( + Map<String, dynamic> json) { + return SimpleClassObjectToEnumType( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, _$enumDecodeNullable(_$EnumTypeEnumMap, e)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, _$enumDecode(_$EnumTypeEnumMap, e)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassObjectToEnumTypeToJson( + SimpleClassObjectToEnumType instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, _$EnumTypeEnumMap[e])), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k, _$EnumTypeEnumMap[e])), + }; + +SimpleClassStringToEnumType _$SimpleClassStringToEnumTypeFromJson( + Map<String, dynamic> json) { + return SimpleClassStringToEnumType( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, _$enumDecodeNullable(_$EnumTypeEnumMap, e)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, _$enumDecode(_$EnumTypeEnumMap, e)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassStringToEnumTypeToJson( + SimpleClassStringToEnumType instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, _$EnumTypeEnumMap[e])), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k, _$EnumTypeEnumMap[e])), + }; + +SimpleClassUriToEnumType _$SimpleClassUriToEnumTypeFromJson( + Map<String, dynamic> json) { + return SimpleClassUriToEnumType( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => + MapEntry(Uri.parse(k), _$enumDecodeNullable(_$EnumTypeEnumMap, e)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(Uri.parse(k), _$enumDecode(_$EnumTypeEnumMap, e)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassUriToEnumTypeToJson( + SimpleClassUriToEnumType instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toString(), _$EnumTypeEnumMap[e])), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toString(), _$EnumTypeEnumMap[e])), + }; + +SimpleClassBigIntToInt _$SimpleClassBigIntToIntFromJson( + Map<String, dynamic> json) { + return SimpleClassBigIntToInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(BigInt.parse(k), e as int), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(BigInt.parse(k), e as int), + ), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToIntToJson( + SimpleClassBigIntToInt instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassDateTimeToInt _$SimpleClassDateTimeToIntFromJson( + Map<String, dynamic> json) { + return SimpleClassDateTimeToInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(DateTime.parse(k), e as int), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(DateTime.parse(k), e as int), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToIntToJson( + SimpleClassDateTimeToInt instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toIso8601String(), e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toIso8601String(), e)), + }; + +SimpleClassDynamicToInt _$SimpleClassDynamicToIntFromJson( + Map<String, dynamic> json) { + return SimpleClassDynamicToInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e as int), + ), + Map<String, int>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToIntToJson( + SimpleClassDynamicToInt instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassEnumTypeToInt _$SimpleClassEnumTypeToIntFromJson( + Map<String, dynamic> json) { + return SimpleClassEnumTypeToInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(_$enumDecodeNullable(_$EnumTypeEnumMap, k), e as int), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(_$enumDecode(_$EnumTypeEnumMap, k), e as int), + ), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToIntToJson( + SimpleClassEnumTypeToInt instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + }; + +SimpleClassIntToInt _$SimpleClassIntToIntFromJson(Map<String, dynamic> json) { + return SimpleClassIntToInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(int.parse(k), e as int), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(int.parse(k), e as int), + ), + ); +} + +Map<String, dynamic> _$SimpleClassIntToIntToJson( + SimpleClassIntToInt instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassObjectToInt _$SimpleClassObjectToIntFromJson( + Map<String, dynamic> json) { + return SimpleClassObjectToInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e as int), + ), + Map<String, int>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassObjectToIntToJson( + SimpleClassObjectToInt instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassStringToInt _$SimpleClassStringToIntFromJson( + Map<String, dynamic> json) { + return SimpleClassStringToInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e as int), + ), + Map<String, int>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassStringToIntToJson( + SimpleClassStringToInt instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassUriToInt _$SimpleClassUriToIntFromJson(Map<String, dynamic> json) { + return SimpleClassUriToInt( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(Uri.parse(k), e as int), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(Uri.parse(k), e as int), + ), + ); +} + +Map<String, dynamic> _$SimpleClassUriToIntToJson( + SimpleClassUriToInt instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassBigIntToNum _$SimpleClassBigIntToNumFromJson( + Map<String, dynamic> json) { + return SimpleClassBigIntToNum( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(BigInt.parse(k), e as num), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(BigInt.parse(k), e as num), + ), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToNumToJson( + SimpleClassBigIntToNum instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassDateTimeToNum _$SimpleClassDateTimeToNumFromJson( + Map<String, dynamic> json) { + return SimpleClassDateTimeToNum( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(DateTime.parse(k), e as num), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(DateTime.parse(k), e as num), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToNumToJson( + SimpleClassDateTimeToNum instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toIso8601String(), e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toIso8601String(), e)), + }; + +SimpleClassDynamicToNum _$SimpleClassDynamicToNumFromJson( + Map<String, dynamic> json) { + return SimpleClassDynamicToNum( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e as num), + ), + Map<String, num>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToNumToJson( + SimpleClassDynamicToNum instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassEnumTypeToNum _$SimpleClassEnumTypeToNumFromJson( + Map<String, dynamic> json) { + return SimpleClassEnumTypeToNum( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(_$enumDecodeNullable(_$EnumTypeEnumMap, k), e as num), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(_$enumDecode(_$EnumTypeEnumMap, k), e as num), + ), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToNumToJson( + SimpleClassEnumTypeToNum instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + }; + +SimpleClassIntToNum _$SimpleClassIntToNumFromJson(Map<String, dynamic> json) { + return SimpleClassIntToNum( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(int.parse(k), e as num), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(int.parse(k), e as num), + ), + ); +} + +Map<String, dynamic> _$SimpleClassIntToNumToJson( + SimpleClassIntToNum instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassObjectToNum _$SimpleClassObjectToNumFromJson( + Map<String, dynamic> json) { + return SimpleClassObjectToNum( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e as num), + ), + Map<String, num>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassObjectToNumToJson( + SimpleClassObjectToNum instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassStringToNum _$SimpleClassStringToNumFromJson( + Map<String, dynamic> json) { + return SimpleClassStringToNum( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e as num), + ), + Map<String, num>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassStringToNumToJson( + SimpleClassStringToNum instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassUriToNum _$SimpleClassUriToNumFromJson(Map<String, dynamic> json) { + return SimpleClassUriToNum( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(Uri.parse(k), e as num), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(Uri.parse(k), e as num), + ), + ); +} + +Map<String, dynamic> _$SimpleClassUriToNumToJson( + SimpleClassUriToNum instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassBigIntToObject _$SimpleClassBigIntToObjectFromJson( + Map<String, dynamic> json) { + return SimpleClassBigIntToObject( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(BigInt.parse(k), e), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(BigInt.parse(k), e), + ), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToObjectToJson( + SimpleClassBigIntToObject instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassDateTimeToObject _$SimpleClassDateTimeToObjectFromJson( + Map<String, dynamic> json) { + return SimpleClassDateTimeToObject( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(DateTime.parse(k), e), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(DateTime.parse(k), e), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToObjectToJson( + SimpleClassDateTimeToObject instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toIso8601String(), e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toIso8601String(), e)), + }; + +SimpleClassDynamicToObject _$SimpleClassDynamicToObjectFromJson( + Map<String, dynamic> json) { + return SimpleClassDynamicToObject( + json['value'] as Map<String, dynamic>, + json['nullable'] as Map<String, dynamic>, + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToObjectToJson( + SimpleClassDynamicToObject instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassEnumTypeToObject _$SimpleClassEnumTypeToObjectFromJson( + Map<String, dynamic> json) { + return SimpleClassEnumTypeToObject( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(_$enumDecodeNullable(_$EnumTypeEnumMap, k), e), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(_$enumDecode(_$EnumTypeEnumMap, k), e), + ), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToObjectToJson( + SimpleClassEnumTypeToObject instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + }; + +SimpleClassIntToObject _$SimpleClassIntToObjectFromJson( + Map<String, dynamic> json) { + return SimpleClassIntToObject( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(int.parse(k), e), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(int.parse(k), e), + ), + ); +} + +Map<String, dynamic> _$SimpleClassIntToObjectToJson( + SimpleClassIntToObject instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassObjectToObject _$SimpleClassObjectToObjectFromJson( + Map<String, dynamic> json) { + return SimpleClassObjectToObject( + json['value'] as Map<String, dynamic>, + json['nullable'] as Map<String, dynamic>, + ); +} + +Map<String, dynamic> _$SimpleClassObjectToObjectToJson( + SimpleClassObjectToObject instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassStringToObject _$SimpleClassStringToObjectFromJson( + Map<String, dynamic> json) { + return SimpleClassStringToObject( + json['value'] as Map<String, dynamic>, + json['nullable'] as Map<String, dynamic>, + ); +} + +Map<String, dynamic> _$SimpleClassStringToObjectToJson( + SimpleClassStringToObject instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassUriToObject _$SimpleClassUriToObjectFromJson( + Map<String, dynamic> json) { + return SimpleClassUriToObject( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(Uri.parse(k), e), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(Uri.parse(k), e), + ), + ); +} + +Map<String, dynamic> _$SimpleClassUriToObjectToJson( + SimpleClassUriToObject instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassBigIntToString _$SimpleClassBigIntToStringFromJson( + Map<String, dynamic> json) { + return SimpleClassBigIntToString( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(BigInt.parse(k), e as String), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(BigInt.parse(k), e as String), + ), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToStringToJson( + SimpleClassBigIntToString instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassDateTimeToString _$SimpleClassDateTimeToStringFromJson( + Map<String, dynamic> json) { + return SimpleClassDateTimeToString( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(DateTime.parse(k), e as String), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(DateTime.parse(k), e as String), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToStringToJson( + SimpleClassDateTimeToString instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toIso8601String(), e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toIso8601String(), e)), + }; + +SimpleClassDynamicToString _$SimpleClassDynamicToStringFromJson( + Map<String, dynamic> json) { + return SimpleClassDynamicToString( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e as String), + ), + Map<String, String>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToStringToJson( + SimpleClassDynamicToString instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassEnumTypeToString _$SimpleClassEnumTypeToStringFromJson( + Map<String, dynamic> json) { + return SimpleClassEnumTypeToString( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => + MapEntry(_$enumDecodeNullable(_$EnumTypeEnumMap, k), e as String), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(_$enumDecode(_$EnumTypeEnumMap, k), e as String), + ), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToStringToJson( + SimpleClassEnumTypeToString instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + 'nullable': + instance.nullable.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e)), + }; + +SimpleClassIntToString _$SimpleClassIntToStringFromJson( + Map<String, dynamic> json) { + return SimpleClassIntToString( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(int.parse(k), e as String), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(int.parse(k), e as String), + ), + ); +} + +Map<String, dynamic> _$SimpleClassIntToStringToJson( + SimpleClassIntToString instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassObjectToString _$SimpleClassObjectToStringFromJson( + Map<String, dynamic> json) { + return SimpleClassObjectToString( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e as String), + ), + Map<String, String>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassObjectToStringToJson( + SimpleClassObjectToString instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassStringToString _$SimpleClassStringToStringFromJson( + Map<String, dynamic> json) { + return SimpleClassStringToString( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e as String), + ), + Map<String, String>.from(json['nullable'] as Map), + ); +} + +Map<String, dynamic> _$SimpleClassStringToStringToJson( + SimpleClassStringToString instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; + +SimpleClassUriToString _$SimpleClassUriToStringFromJson( + Map<String, dynamic> json) { + return SimpleClassUriToString( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(Uri.parse(k), e as String), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(Uri.parse(k), e as String), + ), + ); +} + +Map<String, dynamic> _$SimpleClassUriToStringToJson( + SimpleClassUriToString instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k.toString(), e)), + 'nullable': instance.nullable.map((k, e) => MapEntry(k.toString(), e)), + }; + +SimpleClassBigIntToUri _$SimpleClassBigIntToUriFromJson( + Map<String, dynamic> json) { + return SimpleClassBigIntToUri( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => + MapEntry(BigInt.parse(k), e == null ? null : Uri.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(BigInt.parse(k), Uri.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToUriToJson( + SimpleClassBigIntToUri instance) => + <String, dynamic>{ + 'value': + instance.value?.map((k, e) => MapEntry(k.toString(), e?.toString())), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toString(), e.toString())), + }; + +SimpleClassDateTimeToUri _$SimpleClassDateTimeToUriFromJson( + Map<String, dynamic> json) { + return SimpleClassDateTimeToUri( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry( + DateTime.parse(k), e == null ? null : Uri.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(DateTime.parse(k), Uri.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToUriToJson( + SimpleClassDateTimeToUri instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(k.toIso8601String(), e?.toString())), + 'nullable': instance.nullable + .map((k, e) => MapEntry(k.toIso8601String(), e.toString())), + }; + +SimpleClassDynamicToUri _$SimpleClassDynamicToUriFromJson( + Map<String, dynamic> json) { + return SimpleClassDynamicToUri( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e == null ? null : Uri.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, Uri.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToUriToJson( + SimpleClassDynamicToUri instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, e?.toString())), + 'nullable': instance.nullable.map((k, e) => MapEntry(k, e.toString())), + }; + +SimpleClassEnumTypeToUri _$SimpleClassEnumTypeToUriFromJson( + Map<String, dynamic> json) { + return SimpleClassEnumTypeToUri( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(_$enumDecodeNullable(_$EnumTypeEnumMap, k), + e == null ? null : Uri.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => + MapEntry(_$enumDecode(_$EnumTypeEnumMap, k), Uri.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToUriToJson( + SimpleClassEnumTypeToUri instance) => + <String, dynamic>{ + 'value': instance.value + ?.map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e?.toString())), + 'nullable': instance.nullable + .map((k, e) => MapEntry(_$EnumTypeEnumMap[k], e.toString())), + }; + +SimpleClassIntToUri _$SimpleClassIntToUriFromJson(Map<String, dynamic> json) { + return SimpleClassIntToUri( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => + MapEntry(int.parse(k), e == null ? null : Uri.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(int.parse(k), Uri.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassIntToUriToJson( + SimpleClassIntToUri instance) => + <String, dynamic>{ + 'value': + instance.value?.map((k, e) => MapEntry(k.toString(), e?.toString())), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toString(), e.toString())), + }; + +SimpleClassObjectToUri _$SimpleClassObjectToUriFromJson( + Map<String, dynamic> json) { + return SimpleClassObjectToUri( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e == null ? null : Uri.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, Uri.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassObjectToUriToJson( + SimpleClassObjectToUri instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, e?.toString())), + 'nullable': instance.nullable.map((k, e) => MapEntry(k, e.toString())), + }; + +SimpleClassStringToUri _$SimpleClassStringToUriFromJson( + Map<String, dynamic> json) { + return SimpleClassStringToUri( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => MapEntry(k, e == null ? null : Uri.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(k, Uri.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassStringToUriToJson( + SimpleClassStringToUri instance) => + <String, dynamic>{ + 'value': instance.value?.map((k, e) => MapEntry(k, e?.toString())), + 'nullable': instance.nullable.map((k, e) => MapEntry(k, e.toString())), + }; + +SimpleClassUriToUri _$SimpleClassUriToUriFromJson(Map<String, dynamic> json) { + return SimpleClassUriToUri( + (json['value'] as Map<String, dynamic>)?.map( + (k, e) => + MapEntry(Uri.parse(k), e == null ? null : Uri.parse(e as String)), + ), + (json['nullable'] as Map<String, dynamic>).map( + (k, e) => MapEntry(Uri.parse(k), Uri.parse(e as String)), + ), + ); +} + +Map<String, dynamic> _$SimpleClassUriToUriToJson( + SimpleClassUriToUri instance) => + <String, dynamic>{ + 'value': + instance.value?.map((k, e) => MapEntry(k.toString(), e?.toString())), + 'nullable': + instance.nullable.map((k, e) => MapEntry(k.toString(), e.toString())), + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_num.dart b/json_serializable-3.5.2/test/supported_types/input.type_num.dart new file mode 100644 index 000000000..587656485 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_num.dart @@ -0,0 +1,28 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'input.type_num.g.dart'; + +@JsonSerializable() +class SimpleClass { + final num value; + + @JsonKey(nullable: false) + final num nullable; + + @JsonKey(defaultValue: 88.6) + num withDefault; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_num.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_num.g.dart new file mode 100644 index 000000000..ddca5a84a --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_num.g.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_num.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'] as num, + json['nullable'] as num, + )..withDefault = json['withDefault'] as num ?? 88.6; +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + 'withDefault': instance.withDefault, + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_object.dart b/json_serializable-3.5.2/test/supported_types/input.type_object.dart new file mode 100644 index 000000000..06bba9e4b --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_object.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'input.type_object.g.dart'; + +@JsonSerializable() +class SimpleClass { + final Object value; + + @JsonKey(nullable: false) + final Object nullable; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_object.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_object.g.dart new file mode 100644 index 000000000..e2dafc620 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_object.g.dart @@ -0,0 +1,20 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_object.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'], + json['nullable'], + ); +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_set.dart b/json_serializable-3.5.2/test/supported_types/input.type_set.dart new file mode 100644 index 000000000..395345e2c --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_set.dart @@ -0,0 +1,245 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; +import 'enum_type.dart'; + +part 'input.type_set.g.dart'; + +@JsonSerializable() +class SimpleClass { + final Set value; + + @JsonKey(nullable: false) + final Set nullable; + + @JsonKey(defaultValue: {42, true, false, null}) + Set withDefault; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} + +@JsonSerializable() +class SimpleClassBigInt { + final Set<BigInt> value; + + @JsonKey(nullable: false) + final Set<BigInt> nullable; + + SimpleClassBigInt( + this.value, + this.nullable, + ); + + factory SimpleClassBigInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassBigIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBigIntToJson(this); +} + +@JsonSerializable() +class SimpleClassBool { + final Set<bool> value; + + @JsonKey(nullable: false) + final Set<bool> nullable; + + SimpleClassBool( + this.value, + this.nullable, + ); + + factory SimpleClassBool.fromJson(Map<String, dynamic> json) => + _$SimpleClassBoolFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassBoolToJson(this); +} + +@JsonSerializable() +class SimpleClassDateTime { + final Set<DateTime> value; + + @JsonKey(nullable: false) + final Set<DateTime> nullable; + + SimpleClassDateTime( + this.value, + this.nullable, + ); + + factory SimpleClassDateTime.fromJson(Map<String, dynamic> json) => + _$SimpleClassDateTimeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDateTimeToJson(this); +} + +@JsonSerializable() +class SimpleClassDouble { + final Set<double> value; + + @JsonKey(nullable: false) + final Set<double> nullable; + + SimpleClassDouble( + this.value, + this.nullable, + ); + + factory SimpleClassDouble.fromJson(Map<String, dynamic> json) => + _$SimpleClassDoubleFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDoubleToJson(this); +} + +@JsonSerializable() +class SimpleClassDuration { + final Set<Duration> value; + + @JsonKey(nullable: false) + final Set<Duration> nullable; + + SimpleClassDuration( + this.value, + this.nullable, + ); + + factory SimpleClassDuration.fromJson(Map<String, dynamic> json) => + _$SimpleClassDurationFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDurationToJson(this); +} + +@JsonSerializable() +class SimpleClassDynamic { + final Set<dynamic> value; + + @JsonKey(nullable: false) + final Set<dynamic> nullable; + + SimpleClassDynamic( + this.value, + this.nullable, + ); + + factory SimpleClassDynamic.fromJson(Map<String, dynamic> json) => + _$SimpleClassDynamicFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassDynamicToJson(this); +} + +@JsonSerializable() +class SimpleClassEnumType { + final Set<EnumType> value; + + @JsonKey(nullable: false) + final Set<EnumType> nullable; + + SimpleClassEnumType( + this.value, + this.nullable, + ); + + factory SimpleClassEnumType.fromJson(Map<String, dynamic> json) => + _$SimpleClassEnumTypeFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassEnumTypeToJson(this); +} + +@JsonSerializable() +class SimpleClassInt { + final Set<int> value; + + @JsonKey(nullable: false) + final Set<int> nullable; + + SimpleClassInt( + this.value, + this.nullable, + ); + + factory SimpleClassInt.fromJson(Map<String, dynamic> json) => + _$SimpleClassIntFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassIntToJson(this); +} + +@JsonSerializable() +class SimpleClassNum { + final Set<num> value; + + @JsonKey(nullable: false) + final Set<num> nullable; + + SimpleClassNum( + this.value, + this.nullable, + ); + + factory SimpleClassNum.fromJson(Map<String, dynamic> json) => + _$SimpleClassNumFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassNumToJson(this); +} + +@JsonSerializable() +class SimpleClassObject { + final Set<Object> value; + + @JsonKey(nullable: false) + final Set<Object> nullable; + + SimpleClassObject( + this.value, + this.nullable, + ); + + factory SimpleClassObject.fromJson(Map<String, dynamic> json) => + _$SimpleClassObjectFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassObjectToJson(this); +} + +@JsonSerializable() +class SimpleClassString { + final Set<String> value; + + @JsonKey(nullable: false) + final Set<String> nullable; + + SimpleClassString( + this.value, + this.nullable, + ); + + factory SimpleClassString.fromJson(Map<String, dynamic> json) => + _$SimpleClassStringFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassStringToJson(this); +} + +@JsonSerializable() +class SimpleClassUri { + final Set<Uri> value; + + @JsonKey(nullable: false) + final Set<Uri> nullable; + + SimpleClassUri( + this.value, + this.nullable, + ); + + factory SimpleClassUri.fromJson(Map<String, dynamic> json) => + _$SimpleClassUriFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassUriToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_set.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_set.g.dart new file mode 100644 index 000000000..3958ec345 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_set.g.dart @@ -0,0 +1,234 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_set.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + (json['value'] as List)?.toSet(), + (json['nullable'] as List).toSet(), + )..withDefault = + (json['withDefault'] as List)?.toSet() ?? {42, true, false, null}; +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + 'withDefault': instance.withDefault?.toList(), + }; + +SimpleClassBigInt _$SimpleClassBigIntFromJson(Map<String, dynamic> json) { + return SimpleClassBigInt( + (json['value'] as List) + ?.map((e) => e == null ? null : BigInt.parse(e as String)) + ?.toSet(), + (json['nullable'] as List).map((e) => BigInt.parse(e as String)).toSet(), + ); +} + +Map<String, dynamic> _$SimpleClassBigIntToJson(SimpleClassBigInt instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => e?.toString())?.toList(), + 'nullable': instance.nullable.map((e) => e.toString()).toList(), + }; + +SimpleClassBool _$SimpleClassBoolFromJson(Map<String, dynamic> json) { + return SimpleClassBool( + (json['value'] as List)?.map((e) => e as bool)?.toSet(), + (json['nullable'] as List).map((e) => e as bool).toSet(), + ); +} + +Map<String, dynamic> _$SimpleClassBoolToJson(SimpleClassBool instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassDateTime _$SimpleClassDateTimeFromJson(Map<String, dynamic> json) { + return SimpleClassDateTime( + (json['value'] as List) + ?.map((e) => e == null ? null : DateTime.parse(e as String)) + ?.toSet(), + (json['nullable'] as List).map((e) => DateTime.parse(e as String)).toSet(), + ); +} + +Map<String, dynamic> _$SimpleClassDateTimeToJson( + SimpleClassDateTime instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => e?.toIso8601String())?.toList(), + 'nullable': instance.nullable.map((e) => e.toIso8601String()).toList(), + }; + +SimpleClassDouble _$SimpleClassDoubleFromJson(Map<String, dynamic> json) { + return SimpleClassDouble( + (json['value'] as List)?.map((e) => (e as num)?.toDouble())?.toSet(), + (json['nullable'] as List).map((e) => (e as num).toDouble()).toSet(), + ); +} + +Map<String, dynamic> _$SimpleClassDoubleToJson(SimpleClassDouble instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassDuration _$SimpleClassDurationFromJson(Map<String, dynamic> json) { + return SimpleClassDuration( + (json['value'] as List) + ?.map((e) => e == null ? null : Duration(microseconds: e as int)) + ?.toSet(), + (json['nullable'] as List) + .map((e) => Duration(microseconds: e as int)) + .toSet(), + ); +} + +Map<String, dynamic> _$SimpleClassDurationToJson( + SimpleClassDuration instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => e?.inMicroseconds)?.toList(), + 'nullable': instance.nullable.map((e) => e.inMicroseconds).toList(), + }; + +SimpleClassDynamic _$SimpleClassDynamicFromJson(Map<String, dynamic> json) { + return SimpleClassDynamic( + (json['value'] as List)?.toSet(), + (json['nullable'] as List).toSet(), + ); +} + +Map<String, dynamic> _$SimpleClassDynamicToJson(SimpleClassDynamic instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassEnumType _$SimpleClassEnumTypeFromJson(Map<String, dynamic> json) { + return SimpleClassEnumType( + (json['value'] as List) + ?.map((e) => _$enumDecodeNullable(_$EnumTypeEnumMap, e)) + ?.toSet(), + (json['nullable'] as List) + .map((e) => _$enumDecode(_$EnumTypeEnumMap, e)) + .toSet(), + ); +} + +Map<String, dynamic> _$SimpleClassEnumTypeToJson( + SimpleClassEnumType instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => _$EnumTypeEnumMap[e])?.toList(), + 'nullable': instance.nullable.map((e) => _$EnumTypeEnumMap[e]).toList(), + }; + +T _$enumDecode<T>( + Map<T, dynamic> enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + throw ArgumentError('A value must be provided. Supported values: ' + '${enumValues.values.join(', ')}'); + } + + final value = enumValues.entries + .singleWhere((e) => e.value == source, orElse: () => null) + ?.key; + + if (value == null && unknownValue == null) { + throw ArgumentError('`$source` is not one of the supported values: ' + '${enumValues.values.join(', ')}'); + } + return value ?? unknownValue; +} + +T _$enumDecodeNullable<T>( + Map<T, dynamic> enumValues, + dynamic source, { + T unknownValue, +}) { + if (source == null) { + return null; + } + return _$enumDecode<T>(enumValues, source, unknownValue: unknownValue); +} + +const _$EnumTypeEnumMap = { + EnumType.alpha: 'alpha', + EnumType.beta: 'beta', + EnumType.gamma: 'gamma', + EnumType.delta: 'delta', +}; + +SimpleClassInt _$SimpleClassIntFromJson(Map<String, dynamic> json) { + return SimpleClassInt( + (json['value'] as List)?.map((e) => e as int)?.toSet(), + (json['nullable'] as List).map((e) => e as int).toSet(), + ); +} + +Map<String, dynamic> _$SimpleClassIntToJson(SimpleClassInt instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassNum _$SimpleClassNumFromJson(Map<String, dynamic> json) { + return SimpleClassNum( + (json['value'] as List)?.map((e) => e as num)?.toSet(), + (json['nullable'] as List).map((e) => e as num).toSet(), + ); +} + +Map<String, dynamic> _$SimpleClassNumToJson(SimpleClassNum instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassObject _$SimpleClassObjectFromJson(Map<String, dynamic> json) { + return SimpleClassObject( + (json['value'] as List)?.toSet(), + (json['nullable'] as List).toSet(), + ); +} + +Map<String, dynamic> _$SimpleClassObjectToJson(SimpleClassObject instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassString _$SimpleClassStringFromJson(Map<String, dynamic> json) { + return SimpleClassString( + (json['value'] as List)?.map((e) => e as String)?.toSet(), + (json['nullable'] as List).map((e) => e as String).toSet(), + ); +} + +Map<String, dynamic> _$SimpleClassStringToJson(SimpleClassString instance) => + <String, dynamic>{ + 'value': instance.value?.toList(), + 'nullable': instance.nullable.toList(), + }; + +SimpleClassUri _$SimpleClassUriFromJson(Map<String, dynamic> json) { + return SimpleClassUri( + (json['value'] as List) + ?.map((e) => e == null ? null : Uri.parse(e as String)) + ?.toSet(), + (json['nullable'] as List).map((e) => Uri.parse(e as String)).toSet(), + ); +} + +Map<String, dynamic> _$SimpleClassUriToJson(SimpleClassUri instance) => + <String, dynamic>{ + 'value': instance.value?.map((e) => e?.toString())?.toList(), + 'nullable': instance.nullable.map((e) => e.toString()).toList(), + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_string.dart b/json_serializable-3.5.2/test/supported_types/input.type_string.dart new file mode 100644 index 000000000..8dc10f032 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_string.dart @@ -0,0 +1,28 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'input.type_string.g.dart'; + +@JsonSerializable() +class SimpleClass { + final String value; + + @JsonKey(nullable: false) + final String nullable; + + @JsonKey(defaultValue: 'a string') + String withDefault; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_string.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_string.g.dart new file mode 100644 index 000000000..d3ab769db --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_string.g.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_string.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'] as String, + json['nullable'] as String, + )..withDefault = json['withDefault'] as String ?? 'a string'; +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value, + 'nullable': instance.nullable, + 'withDefault': instance.withDefault, + }; diff --git a/json_serializable-3.5.2/test/supported_types/input.type_uri.dart b/json_serializable-3.5.2/test/supported_types/input.type_uri.dart new file mode 100644 index 000000000..ce41b79ca --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_uri.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2020, 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. + +import 'package:json_annotation/json_annotation.dart'; + +part 'input.type_uri.g.dart'; + +@JsonSerializable() +class SimpleClass { + final Uri value; + + @JsonKey(nullable: false) + final Uri nullable; + + SimpleClass( + this.value, + this.nullable, + ); + + factory SimpleClass.fromJson(Map<String, dynamic> json) => + _$SimpleClassFromJson(json); + + Map<String, dynamic> toJson() => _$SimpleClassToJson(this); +} diff --git a/json_serializable-3.5.2/test/supported_types/input.type_uri.g.dart b/json_serializable-3.5.2/test/supported_types/input.type_uri.g.dart new file mode 100644 index 000000000..665a3b5a3 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/input.type_uri.g.dart @@ -0,0 +1,20 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'input.type_uri.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SimpleClass _$SimpleClassFromJson(Map<String, dynamic> json) { + return SimpleClass( + json['value'] == null ? null : Uri.parse(json['value'] as String), + Uri.parse(json['nullable'] as String), + ); +} + +Map<String, dynamic> _$SimpleClassToJson(SimpleClass instance) => + <String, dynamic>{ + 'value': instance.value?.toString(), + 'nullable': instance.nullable.toString(), + }; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.bigint_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.bigint_test.dart new file mode 100644 index 000000000..d185cabd3 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.bigint_test.dart @@ -0,0 +1,41 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_bigint.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = '12345'; +final _altValue = '67890'; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.bool_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.bool_test.dart new file mode 100644 index 000000000..52f6764ce --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.bool_test.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_bool.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = true; +final _altValue = false; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, + 'withDefault': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, + 'withDefault': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.dart new file mode 100644 index 000000000..ce7436949 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = 42; +final _altValue = 43; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, + 'withDefault': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, + 'withDefault': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.datetime_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.datetime_test.dart new file mode 100644 index 000000000..ec9f36619 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.datetime_test.dart @@ -0,0 +1,41 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_datetime.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = '2020-01-01T00:00:00.000'; +final _altValue = '2018-01-01T00:00:00.000'; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.double_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.double_test.dart new file mode 100644 index 000000000..466abab43 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.double_test.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_double.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = 3.14; +final _altValue = 6.28; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, + 'withDefault': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, + 'withDefault': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.duration_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.duration_test.dart new file mode 100644 index 000000000..463298ea0 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.duration_test.dart @@ -0,0 +1,41 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_duration.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = 1234; +final _altValue = 2345; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.enumtype_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.enumtype_test.dart new file mode 100644 index 000000000..321452c71 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.enumtype_test.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_enumtype.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = 'alpha'; +final _altValue = 'beta'; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, + 'withDefault': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, + 'withDefault': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.int_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.int_test.dart new file mode 100644 index 000000000..53d59319c --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.int_test.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_int.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = 42; +final _altValue = 43; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, + 'withDefault': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, + 'withDefault': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.iterable_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.iterable_test.dart new file mode 100644 index 000000000..301725643 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.iterable_test.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_iterable.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = [42, true, false, null]; +final _altValue = [43, false]; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, + 'withDefault': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, + 'withDefault': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.list_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.list_test.dart new file mode 100644 index 000000000..96ccc6751 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.list_test.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_list.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = [42, true, false, null]; +final _altValue = [43, false]; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, + 'withDefault': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, + 'withDefault': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.map_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.map_test.dart new file mode 100644 index 000000000..62b062586 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.map_test.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_map.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = {'a': 1}; +final _altValue = {'b': 2}; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, + 'withDefault': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, + 'withDefault': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.num_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.num_test.dart new file mode 100644 index 000000000..0ab60c852 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.num_test.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_num.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = 88.6; +final _altValue = 29; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, + 'withDefault': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, + 'withDefault': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.object_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.object_test.dart new file mode 100644 index 000000000..30b9c8642 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.object_test.dart @@ -0,0 +1,41 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_object.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = null; +final _altValue = 'Object'; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.set_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.set_test.dart new file mode 100644 index 000000000..10db9945f --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.set_test.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_set.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = [42, true, false, null]; +final _altValue = [43, false]; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, + 'withDefault': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, + 'withDefault': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.string_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.string_test.dart new file mode 100644 index 000000000..04556ee90 --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.string_test.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_string.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = 'a string'; +final _altValue = 'another string'; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, + 'withDefault': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, + 'withDefault': _altValue, +}; diff --git a/json_serializable-3.5.2/test/supported_types/type_test.uri_test.dart b/json_serializable-3.5.2/test/supported_types/type_test.uri_test.dart new file mode 100644 index 000000000..6784d840a --- /dev/null +++ b/json_serializable-3.5.2/test/supported_types/type_test.uri_test.dart @@ -0,0 +1,41 @@ +// Copyright (c) 2020, 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. + +// ignore_for_file: prefer_const_declarations + +@TestOn('vm') +import 'package:test/test.dart'; + +import '../test_utils.dart'; +import 'input.type_uri.dart'; + +void main() { + test('round trip', () { + final object = SimpleClass.fromJson(_emptyInput); + expect(loudEncode(object), loudEncode(_defaultOutput)); + }); + + test('round trip alternate values', () { + final object = SimpleClass.fromJson(_nonDefaultJson); + expect(loudEncode(object), loudEncode(_nonDefaultJson)); + expect(loudEncode(object), isNot(loudEncode(_defaultOutput))); + }); +} + +final _defaultValue = 'https://example.com'; +final _altValue = 'https://dart.dev'; + +final _emptyInput = <String, dynamic>{ + 'nullable': _defaultValue, +}; + +final _defaultOutput = { + 'value': null, + 'nullable': _defaultValue, +}; + +final _nonDefaultJson = { + 'value': null, + 'nullable': _altValue, +}; diff --git a/json_serializable-3.5.2/test/test_sources/test_sources.dart b/json_serializable-3.5.2/test/test_sources/test_sources.dart new file mode 100644 index 000000000..198398e53 --- /dev/null +++ b/json_serializable-3.5.2/test/test_sources/test_sources.dart @@ -0,0 +1,81 @@ +import 'package:json_annotation/json_annotation.dart'; + +@JsonSerializable() +class ConfigurationImplicitDefaults { + int field; +} + +@JsonSerializable( + anyMap: false, + checked: false, + createFactory: true, + createToJson: true, + disallowUnrecognizedKeys: false, + explicitToJson: false, + fieldRename: FieldRename.none, + ignoreUnannotated: false, + includeIfNull: true, + nullable: true, + genericArgumentFactories: false, +) +class ConfigurationExplicitDefaults { + int field; +} + +@JsonSerializable(createFactory: false) +class IncludeIfNullAll { + @JsonKey(includeIfNull: true) + int number; + String str; +} + +@JsonSerializable(createToJson: false) +class FromJsonOptionalParameters { + final ChildWithFromJson child; + + FromJsonOptionalParameters(this.child); +} + +class ChildWithFromJson { + //ignore: avoid_unused_constructor_parameters + ChildWithFromJson.fromJson(json, {initValue = false}); +} + +@JsonSerializable() +class ParentObject { + int number; + String str; + ChildObject child; +} + +@JsonSerializable() +class ChildObject { + int number; + String str; +} + +@JsonSerializable() +class ParentObjectWithChildren { + int number; + String str; + List<ChildObject> children; +} + +@JsonSerializable() +class ParentObjectWithDynamicChildren { + int number; + String str; + List<dynamic> children; +} + +@JsonSerializable(createFactory: false, explicitToJson: true) +class TrivialNestedNullable { + TrivialNestedNullable child; + int otherField; +} + +@JsonSerializable(createFactory: false, nullable: false, explicitToJson: true) +class TrivialNestedNonNullable { + TrivialNestedNonNullable child; + int otherField; +} diff --git a/json_serializable-3.5.2/test/test_utils.dart b/json_serializable-3.5.2/test/test_utils.dart new file mode 100644 index 000000000..51e6190f4 --- /dev/null +++ b/json_serializable-3.5.2/test/test_utils.dart @@ -0,0 +1,39 @@ +// Copyright (c) 2015, 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. + +import 'dart:convert'; + +import 'package:test/test.dart'; + +// ignore: deprecated_member_use +final throwsCastError = throwsA(isA<CastError>()); + +T roundTripObject<T>(T object, T Function(Map<String, dynamic> json) factory) { + final data = loudEncode(object); + + final object2 = factory(json.decode(data) as Map<String, dynamic>); + + expect(object2, equals(object)); + + final json2 = loudEncode(object2); + + expect(json2, equals(data)); + return object2; +} + +/// Prints out nested causes before throwing `JsonUnsupportedObjectError`. +String loudEncode(Object object) { + try { + return const JsonEncoder.withIndent(' ').convert(object); + } on JsonUnsupportedObjectError catch (e) // ignore: avoid_catching_errors + { + var error = e; + do { + final cause = error.cause; + print(cause); + error = (cause is JsonUnsupportedObjectError) ? cause : null; + } while (error != null); + rethrow; + } +} diff --git a/json_serializable-3.5.2/test/utils_test.dart b/json_serializable-3.5.2/test/utils_test.dart new file mode 100644 index 000000000..aedc7d0a1 --- /dev/null +++ b/json_serializable-3.5.2/test/utils_test.dart @@ -0,0 +1,53 @@ +// 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. + +@TestOn('vm') + +import 'package:test/test.dart'; + +import 'package:json_serializable/src/utils.dart'; + +const _kebabItems = { + 'simple': 'simple', + 'twoWords': 'two-words', + 'FirstBig': 'first-big' +}; + +const _pascalItems = { + 'simple': 'Simple', + 'twoWords': 'TwoWords', + 'FirstBig': 'FirstBig' +}; + +const _snakeItems = { + 'simple': 'simple', + 'twoWords': 'two_words', + 'FirstBig': 'first_big' +}; + +void main() { + group('kebab', () { + for (final entry in _kebabItems.entries) { + test('"${entry.key}"', () { + expect(kebabCase(entry.key), entry.value); + }); + } + }); + + group('pascal', () { + for (final entry in _pascalItems.entries) { + test('"${entry.key}"', () { + expect(pascalCase(entry.key), entry.value); + }); + } + }); + + group('snake', () { + for (final entry in _snakeItems.entries) { + test('"${entry.key}"', () { + expect(snakeCase(entry.key), entry.value); + }); + } + }); +} diff --git a/json_serializable-3.5.2/tool/doc_builder.dart b/json_serializable-3.5.2/tool/doc_builder.dart new file mode 100644 index 000000000..37e5de5db --- /dev/null +++ b/json_serializable-3.5.2/tool/doc_builder.dart @@ -0,0 +1,191 @@ +// Copyright (c) 2019, 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. +import 'dart:async'; + +import 'package:analyzer/dart/element/element.dart'; +import 'package:build/build.dart'; +import 'package:json_serializable/src/utils.dart'; +import 'package:pub_semver/pub_semver.dart'; +import 'package:source_gen/source_gen.dart'; +import 'package:yaml/yaml.dart'; + +Builder docBuilder([_]) => _DocBuilder(); + +const _jsonKey = 'JsonKey'; +const _jsonSerializable = 'JsonSerializable'; + +class _DocBuilder extends Builder { + @override + FutureOr<void> build(BuildStep buildStep) async { + final lockFileAssetId = AssetId(buildStep.inputId.package, 'pubspec.lock'); + final lockFileContent = await buildStep.readAsString(lockFileAssetId); + final lockFileYaml = + loadYaml(lockFileContent, sourceUrl: lockFileAssetId.uri); + final pkgMap = lockFileYaml['packages'] as YamlMap; + final jsonAnnotationMap = pkgMap['json_annotation'] as YamlMap; + final jsonAnnotationVersionString = jsonAnnotationMap['version'] as String; + + final jsonAnnotationVersion = + Version.parse(jsonAnnotationVersionString.trim()); + + final targetVersion = jsonAnnotationVersion.isPreRelease + ? 'latest' + : jsonAnnotationVersion.toString(); + + final lib = LibraryReader(await buildStep.resolver.libraryFor( + AssetId.resolve('package:json_annotation/json_annotation.dart'))); + + final descriptionMap = <String, _FieldInfo>{}; + + for (var className in _annotationClasses) { + for (var fe in lib + .findType(className) + .fields + .where((fe) => !fe.isStatic && !fe.hasDeprecated)) { + descriptionMap[fe.name] = + _FieldInfo.update(fe, descriptionMap[fe.name]); + } + } + + final buffer = StringBuffer(); + + final sortedValues = descriptionMap.values.toList()..sort(); + + final rows = <List<String>>[ + ['`build.yaml` key', _jsonSerializable, _jsonKey], + ['-', '-', '-'], + for (var info in sortedValues) + [ + info.buildKey, + info.classAnnotationName, + info.fieldAnnotationName, + ], + ]; + + final longest = List<int>.generate(rows.first.length, (_) => 0); + for (var row in rows) { + for (var column = 0; column < longest.length; column++) { + if (row[column].length > longest[column]) { + longest[column] = row[column].length; + } + } + } + + for (var row in rows) { + for (var column = 0; column < longest.length; column++) { + var content = row[column]; + if (content == '-') { + content *= longest[column]; + } else { + content = content.padRight(longest[column]); + } + buffer.write('| $content '); + } + buffer.writeln('|'); + } + + buffer.writeln(); + + for (var info in sortedValues) { + if (info._classField != null) { + buffer.writeln(_link(targetVersion, _jsonSerializable, info.name)); + } + if (info._keyField != null) { + buffer.writeln(_link(targetVersion, _jsonKey, info.name)); + } + } + + await buildStep.writeAsString( + AssetId(buildStep.inputId.package, 'doc/doc.md'), buffer.toString()); + } + + @override + final buildExtensions = const { + r'lib/json_serializable.dart': ['doc/doc.md'] + }; +} + +const _annotationClasses = [_jsonSerializable, _jsonKey]; + +String _anchorUriForName(String owner, String name) => '[$owner.$name]'; + +String _link(String version, String owner, String name) => + '${_anchorUriForName(owner, name)}: ' + 'https://pub.dev/documentation/json_annotation/$version/' + 'json_annotation/$owner/$name.html'; + +class _FieldInfo implements Comparable<_FieldInfo> { + final FieldElement _keyField, _classField; + + String get name => _keyField?.name ?? _classField.name; + + String get classAnnotationName { + if (_classField == null) { + return ''; + } + return _anchorUriForName(_jsonSerializable, name); + } + + String get fieldAnnotationName { + if (_keyField == null) { + return ''; + } + return _anchorUriForName(_jsonKey, name); + } + + String get buildKey { + if (_classField == null) { + return ''; + } + + return snakeCase(_classField.name); + } + + _FieldInfo(this._keyField, this._classField); + + static _FieldInfo update(FieldElement field, _FieldInfo existing) { + final parent = field.enclosingElement.name; + + FieldElement keyField, classField; + switch (parent) { + case _jsonSerializable: + classField = field; + keyField = existing?._keyField; + break; + case _jsonKey: + keyField = field; + classField = existing?._classField; + break; + default: + throw FallThroughError(); + } + + return _FieldInfo(keyField, classField); + } + + @override + int compareTo(_FieldInfo other) { + var value = _sortValue.compareTo(other._sortValue); + + if (value == 0) { + value = name.compareTo(other.name); + } + return value; + } + + int get _sortValue { + if (_classField == null) { + return 0; + } + + if (_keyField == null) { + return -2; + } + + return -1; + } + + @override + String toString() => '_FieldThing($_keyField)'; +} diff --git a/json_serializable-3.5.2/tool/shared.dart b/json_serializable-3.5.2/tool/shared.dart new file mode 100644 index 000000000..3e12e469e --- /dev/null +++ b/json_serializable-3.5.2/tool/shared.dart @@ -0,0 +1,71 @@ +// Copyright (c) 2020, 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. + +import 'dart:io'; + +import 'package:build/build.dart'; +import 'package:yaml/yaml.dart'; + +// Until we have verification in pkg:build and friends +// https://github.com/dart-lang/build/issues/590 +Builder validate(String builderName, Builder builder) { + var buildYaml = loadYaml( + File('build.yaml').readAsStringSync(), + sourceUrl: Uri.parse('build.yaml'), + ) as YamlMap; + + for (var key in ['builders', builderName, 'build_extensions']) { + buildYaml = buildYaml[key] as YamlMap; + } + + final extensions = Set<String>.from(buildYaml['.dart'] as YamlList); + + final codedExtensions = builder.buildExtensions['.dart'].toSet(); + + final tooMany = extensions.difference(codedExtensions); + if (tooMany.isNotEmpty) { + log.warning( + '$builderName: Too many extensions in build.yaml:\n' + '${tooMany.join('\n')}', + ); + } + + final missing = codedExtensions.difference(extensions); + if (missing.isNotEmpty) { + log.warning( + '$builderName: Missing extensions in build.yaml:\n' + '${missing.join('\n')}', + ); + } + + return builder; +} + +class Replacement { + final Pattern existing; + final String replacement; + + const Replacement(this.existing, this.replacement); + + const Replacement.addJsonSerializableKey(String key, bool value) + : existing = '@JsonSerializable(', + replacement = '@JsonSerializable(\n $key: $value,'; + + static String generate( + String inputContent, + Iterable<Replacement> replacements, + ) { + var outputContent = inputContent; + + for (final r in replacements) { + if (!outputContent.contains(r.existing)) { + print('Input string did not contain `${r.existing}` as expected.'); + } else { + outputContent = outputContent.replaceAll(r.existing, r.replacement); + } + } + + return outputContent.replaceAll(',)', ',\n)'); + } +} diff --git a/json_serializable-3.5.2/tool/test_builder.dart b/json_serializable-3.5.2/tool/test_builder.dart new file mode 100644 index 000000000..ea69a84fc --- /dev/null +++ b/json_serializable-3.5.2/tool/test_builder.dart @@ -0,0 +1,208 @@ +// 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. + +import 'dart:async'; +import 'dart:collection'; + +import 'package:build/build.dart'; +import 'package:dart_style/dart_style.dart'; +import 'package:path/path.dart' as p; + +import 'shared.dart'; + +final _formatter = DartFormatter(); + +Builder testBuilder([_]) => validate('_test_builder', const _TestBuilder()); + +class _TestBuilder implements Builder { + const _TestBuilder(); + + @override + FutureOr<void> build(BuildStep buildStep) async { + final baseName = p.basenameWithoutExtension(buildStep.inputId.path); + + final sourceContent = await buildStep.readAsString(buildStep.inputId); + + final factories = + SplayTreeMap.from({'$_kitchenSinkBaseName.dart': 'normal'}); + + for (var config in _fileConfigurationMap[baseName]) { + final extension = _configToExtension(config); + final newId = buildStep.inputId.changeExtension(extension); + + final partName = extension.substring(0, extension.length - 5); + + final replacements = <Replacement>[ + Replacement( + "part '$baseName.g.dart';", + "part '$baseName$partName.g.dart';", + ) + ]; + + if (baseName == _kitchenSinkBaseName) { + final description = _configToName(config.toSet()); + replacements.add(Replacement( + "String get description => '--defaults--';", + "String get description => '$description';", + )); + + factories['$baseName$partName.dart'] = description; + } + + for (var entry in config) { + replacements.addAll(_optionReplacement(baseName, entry)); + } + + final content = Replacement.generate(sourceContent, replacements); + + await buildStep.writeAsString(newId, _formatter.format(content)); + } + + if (baseName == _kitchenSinkBaseName) { + final newId = buildStep.inputId.changeExtension('.factories.dart'); + + final lines = <String>[ + ...factories.entries.map((e) => "import '${e.key}' as ${e.value};"), + 'const factories = [', + ...factories.values.map((e) => '$e.factory,'), + '];', + ]; + + await buildStep.writeAsString(newId, _formatter.format(lines.join('\n'))); + } + } + + @override + Map<String, List<String>> get buildExtensions => + {'.dart': _fileConfigurations}; +} + +const _configReplacements = { + 'any_map': Replacement.addJsonSerializableKey('anyMap', true), + 'checked': Replacement.addJsonSerializableKey('checked', true), + 'non_nullable': Replacement.addJsonSerializableKey('nullable', false), + 'explicit_to_json': + Replacement.addJsonSerializableKey('explicitToJson', true), + 'exclude_null': Replacement.addJsonSerializableKey('includeIfNull', false), +}; + +const _kitchenSinkReplacements = { + 'any_map': [ + Replacement( + 'bool get anyMap => false;', + 'bool get anyMap => true;', + ), + Replacement( + 'class _Factory implements k.KitchenSinkFactory<String, dynamic>', + 'class _Factory implements k.KitchenSinkFactory<dynamic, dynamic>', + ), + Replacement( + 'k.KitchenSink fromJson(Map<String, dynamic> json)', + 'k.KitchenSink fromJson(Map json)', + ), + Replacement( + 'factory KitchenSink.fromJson(Map<String, dynamic> json)', + 'factory KitchenSink.fromJson(Map json)', + ), + ], + 'checked': [ + Replacement( + 'bool get checked => false;', + 'bool get checked => true;', + ) + ], + 'exclude_null': [ + Replacement( + 'bool get excludeNull => false;', + 'bool get excludeNull => true;', + ), + ], + 'explicit_to_json': [ + Replacement( + 'bool get explicitToJson => false;', + 'bool get explicitToJson => true;', + ), + ], + 'non_nullable': [ + Replacement( + 'bool get nullable => true;', + 'bool get nullable => false;', + ), + Replacement( + 'List<T> _defaultList<T>() => null;', + 'List<T> _defaultList<T>() => <T>[];', + ), + Replacement( + 'Set<T> _defaultSet<T>() => null;', + 'Set<T> _defaultSet<T>() => <T>{};', + ), + Replacement( + 'Map<K, V> _defaultMap<K, V>() => null;', + 'Map<String, T> _defaultMap<T>() => <String, T>{};', + ), + Replacement( + 'SimpleObject _defaultSimpleObject() => null;', + 'SimpleObject _defaultSimpleObject() => SimpleObject(42);', + ), + Replacement( + 'StrictKeysObject _defaultStrictKeysObject() => null;', + 'StrictKeysObject _defaultStrictKeysObject() => ' + "StrictKeysObject(10, 'cool');", + ), + Replacement( + 'DateTime dateTime;', + 'DateTime dateTime = DateTime(1981, 6, 5);', + ), + Replacement( + 'BigInt bigInt;', + "BigInt bigInt = BigInt.parse('10000000000000000000');", + ), + ], +}; + +Iterable<Replacement> _optionReplacement( + String baseName, String optionKey) sync* { + yield _configReplacements[optionKey]; + + if (baseName == _kitchenSinkBaseName && + _kitchenSinkReplacements.containsKey(optionKey)) { + yield* _kitchenSinkReplacements[optionKey]; + } +} + +String _configToExtension(Iterable<String> config) => + '.g_${_configToName(config.toSet())}.dart'; + +String _configToName(Set<String> config) => + (config.toList()..sort()).join('__'); + +List<String> get _fileConfigurations => _fileConfigurationMap.values + .expand((v) => v) + .map(_configToExtension) + .followedBy(['.factories.dart']) + .toSet() + .toList() + ..sort(); + +const _kitchenSinkBaseName = 'kitchen_sink'; + +const _fileConfigurationMap = <String, Set<Set<String>>>{ + _kitchenSinkBaseName: { + {'any_map', 'checked', 'non_nullable'}, + {'any_map', 'non_nullable'}, + {'any_map'}, + {'exclude_null'}, + {'non_nullable'}, + {'exclude_null', 'non_nullable'}, + {'explicit_to_json'}, + }, + 'default_value': { + {'any_map', 'checked'}, + }, + 'generic_class': <Set<String>>{}, + 'json_test_example': { + {'any_map'}, + {'non_nullable'}, + } +}; diff --git a/json_serializable-3.5.2/tool/test_type_builder.dart b/json_serializable-3.5.2/tool/test_type_builder.dart new file mode 100644 index 000000000..a1eb4d18e --- /dev/null +++ b/json_serializable-3.5.2/tool/test_type_builder.dart @@ -0,0 +1,172 @@ +// 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. + +import 'dart:async'; + +import 'package:build/build.dart'; +import 'package:collection/collection.dart'; +import 'package:dart_style/dart_style.dart'; + +import 'shared.dart'; +import 'test_type_data.dart'; + +final _formatter = DartFormatter(); + +const _trivialTypesToTest = { + 'BigInt': TestTypeData( + jsonExpression: "'12345'", + altJsonExpression: "'67890'", + ), + 'bool': TestTypeData( + defaultExpression: 'true', + altJsonExpression: 'false', + ), + 'DateTime': TestTypeData( + jsonExpression: "'2020-01-01T00:00:00.000'", + altJsonExpression: "'2018-01-01T00:00:00.000'", + ), + 'double': TestTypeData( + defaultExpression: '3.14', + altJsonExpression: '6.28', + ), + 'Duration': TestTypeData( + jsonExpression: '1234', + altJsonExpression: '2345', + ), + 'int': TestTypeData( + defaultExpression: '42', + altJsonExpression: '43', + ), + customEnumType: TestTypeData( + defaultExpression: '$customEnumType.alpha', + jsonExpression: "'alpha'", + altJsonExpression: "'beta'", + ), + 'num': TestTypeData( + defaultExpression: '88.6', + altJsonExpression: '29', + ), + 'Object': TestTypeData( + altJsonExpression: "'Object'", + ), + 'String': TestTypeData( + defaultExpression: "'a string'", + altJsonExpression: "'another string'", + ), + 'Uri': TestTypeData( + jsonExpression: "'https://example.com'", + altJsonExpression: "'https://dart.dev'", + ), +}; + +final _typesToTest = { + ..._trivialTypesToTest, + // + // Collection types + // + 'Map': TestTypeData( + defaultExpression: "{'a': 1}", + altJsonExpression: "{'b': 2}", + genericArgs: _iterableGenericArgs + .expand((v) => _mapKeyTypes.map((k) => '$k,$v')) + .toSet(), + ), + 'List': TestTypeData( + defaultExpression: '[$_defaultCollectionExpressions]', + altJsonExpression: '[$_altCollectionExpressions]', + genericArgs: _iterableGenericArgs, + ), + 'Set': TestTypeData( + defaultExpression: '{$_defaultCollectionExpressions}', + jsonExpression: '[$_defaultCollectionExpressions]', + altJsonExpression: '[$_altCollectionExpressions]', + genericArgs: _iterableGenericArgs, + ), + 'Iterable': TestTypeData( + defaultExpression: '[$_defaultCollectionExpressions]', + altJsonExpression: '[$_altCollectionExpressions]', + genericArgs: _iterableGenericArgs, + ), +}; + +const _mapKeyTypes = { + 'BigInt', + 'DateTime', + 'dynamic', + 'EnumType', + 'int', + 'Object', + 'String', + 'Uri', +}; + +final _iterableGenericArgs = ([ + ..._trivialTypesToTest.keys, + 'dynamic', +]..sort(compareAsciiLowerCase)) + .toSet(); + +const _defaultCollectionExpressions = '42, true, false, null'; +const _altCollectionExpressions = '43, false'; + +Builder typeBuilder([_]) => validate('_type_builder', const _TypeBuilder()); + +class _TypeBuilder implements Builder { + const _TypeBuilder(); + + @override + FutureOr<void> build(BuildStep buildStep) async { + final inputId = buildStep.inputId; + + final sourceContent = await buildStep.readAsString(inputId); + + for (var entry in _typesToTest.entries) { + final type = entry.key; + final newId = buildStep.inputId.changeExtension(toTypeExtension(type)); + + await buildStep.writeAsString( + newId, + _formatter.format(entry.value.libContent(sourceContent, type)), + ); + } + } + + @override + Map<String, List<String>> get buildExtensions => { + '.dart': _typesToTest.keys.map(toTypeExtension).toSet().toList()..sort() + }; +} + +Builder typeTestBuilder([_]) => + validate('_type_test_builder', const _TypeTestBuilder()); + +class _TypeTestBuilder implements Builder { + const _TypeTestBuilder(); + + @override + FutureOr<void> build(BuildStep buildStep) async { + final inputId = buildStep.inputId; + + final sourceContent = await buildStep.readAsString(inputId); + + for (var entry in _typesToTest.entries) { + final type = entry.key; + final newId = + buildStep.inputId.changeExtension(_toTypeTestExtension(type)); + + await buildStep.writeAsString( + newId, + entry.value.testContent(sourceContent, type), + ); + } + } + + @override + Map<String, List<String>> get buildExtensions => { + '.dart': _typesToTest.keys.map(_toTypeTestExtension).toSet().toList() + ..sort() + }; +} + +String _toTypeTestExtension(String e) => '.${typeToPathPart(e)}_test.dart'; diff --git a/json_serializable-3.5.2/tool/test_type_data.dart b/json_serializable-3.5.2/tool/test_type_data.dart new file mode 100644 index 000000000..1036e3231 --- /dev/null +++ b/json_serializable-3.5.2/tool/test_type_data.dart @@ -0,0 +1,152 @@ +import 'package:meta/meta.dart'; + +import 'shared.dart'; + +const customEnumType = 'EnumType'; + +const _annotationImport = + "import 'package:json_annotation/json_annotation.dart';"; + +class TestTypeData { + final String defaultExpression; + final String jsonExpression; + final String altJsonExpression; + final Set<String> genericArgs; + + const TestTypeData({ + this.defaultExpression, + String jsonExpression, + @required String altJsonExpression, + this.genericArgs = const {}, + }) : jsonExpression = jsonExpression ?? defaultExpression, + altJsonExpression = + altJsonExpression ?? jsonExpression ?? defaultExpression; + + String libContent(String source, String type) { + const classAnnotationSplit = '@JsonSerializable()'; + + final split = source.split(classAnnotationSplit); + + assert(split.length == 2); + + final newPart = toTypeExtension(type, includeDotDart: false); + + final headerReplacements = [ + if (type == customEnumType || + genericArgs.any((element) => element.contains(customEnumType))) + const Replacement( + _annotationImport, + '$_annotationImport' + "import 'enum_type.dart';", + ), + Replacement( + "part 'input.g.dart';", + "part 'input$newPart.g.dart';", + ) + ]; + + final buffer = + StringBuffer(Replacement.generate(split[0], headerReplacements)); + + final simpleClassContent = '$classAnnotationSplit${split[1]}'; + + buffer.write(Replacement.generate( + simpleClassContent, + _libReplacements(type), + )); + + for (var genericArg in genericArgs) { + final genericArgClassPart = _genericClassPart(genericArg); + + final genericType = '$type<$genericArg>'; + + buffer.write(Replacement.generate( + simpleClassContent.replaceAll( + 'SimpleClass', + 'SimpleClass$genericArgClassPart', + ), + _libReplacements(genericType), + )); + } + + return buffer.toString(); + } + + Iterable<Replacement> _libReplacements(String type) sync* { + yield Replacement( + 'final dynamic value;', + 'final $type value;', + ); + yield Replacement( + 'final dynamic nullable;', + 'final $type nullable;', + ); + + final defaultReplacement = (defaultExpression == null // no default provided + || + type.contains('<') // no support for default values and generic args + ) + ? '' + : _defaultSource + .replaceFirst('42', defaultExpression) + .replaceFirst('dynamic', type); + + yield Replacement( + _defaultSource, + defaultReplacement, + ); + } + + String testContent(String sourceContent, String type) => Replacement.generate( + sourceContent, + _testReplacements(type), + ); + + Iterable<Replacement> _testReplacements(String type) sync* { + yield Replacement( + "import 'input.dart';", + "import 'input.type_${typeToPathPart(type)}.dart';", + ); + + yield Replacement( + ''' +final _defaultValue = 42; +final _altValue = 43; +''', + ''' +final _defaultValue = $jsonExpression; +final _altValue = $altJsonExpression; +''', + ); + + if (defaultExpression == null) { + yield const Replacement( + " 'withDefault': _defaultValue,\n", + '', + ); + yield const Replacement( + " 'withDefault': _altValue,\n", + '', + ); + } + } + + static const _defaultSource = r''' + @JsonKey(defaultValue: 42) + dynamic withDefault; + +'''; +} + +String _genericClassPart(String genericArg) => genericArg + .split(',') + .map((e) => [ + e.substring(0, 1).toUpperCase(), + e.substring(1), + ].join()) + .join('To'); + +String toTypeExtension(String e, {bool includeDotDart = true}) => + '.type_${typeToPathPart(e)}${includeDotDart ? '.dart' : ''}'; + +String typeToPathPart(String type) => type.toLowerCase(); From e4c7b37f336ab73cc38662577a2137613c4276fb Mon Sep 17 00:00:00 2001 From: rmconsole-readonly-wk <gh_rosie-staging+readonly@workiva.com> Date: Mon, 31 Jul 2023 14:45:00 -0500 Subject: [PATCH 2/2] w_dio_5.3.1 (#14) --- dio/pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dio/pubspec.yaml b/dio/pubspec.yaml index 813045f26..285562ce2 100644 --- a/dio/pubspec.yaml +++ b/dio/pubspec.yaml @@ -8,7 +8,7 @@ description: | Files uploading and downloading, Requests timeout, Custom adapters, etc. -version: 5.3.0 +version: 5.3.1 environment: sdk: '>=2.15.0 <3.0.0'