diff --git a/json_annotation/CHANGELOG.md b/json_annotation/CHANGELOG.md index e5cc965b..fed809ee 100644 --- a/json_annotation/CHANGELOG.md +++ b/json_annotation/CHANGELOG.md @@ -1,6 +1,7 @@ ## 4.11.0-wip - -- Add `JsonSerializable.dateTimeUtc` configuration option. +- Add `JsonSerializable.enumFieldRename` configuration option. + ([#1556](https://github.com/google/json_serializable.dart/pull/1556)) +- Add `JsonSerializable.dateTimeUtc` configuration option. ([#1371](https://github.com/google/json_serializable.dart/issues/1371)) ## 4.10.0 diff --git a/json_annotation/lib/src/json_serializable.dart b/json_annotation/lib/src/json_serializable.dart index a2e84c4f..422ae144 100644 --- a/json_annotation/lib/src/json_serializable.dart +++ b/json_annotation/lib/src/json_serializable.dart @@ -8,6 +8,7 @@ import 'allowed_keys_helpers.dart'; import 'checked_helpers.dart'; import 'enum_helpers.dart'; import 'json_converter.dart'; +import 'json_enum.dart' show JsonEnum; import 'json_key.dart'; part 'json_serializable.g.dart'; @@ -175,6 +176,12 @@ class JsonSerializable { /// fields annotated with [JsonKey]. final FieldRename? fieldRename; + /// Default field rename for enum values when not set on [JsonEnum]. + /// + /// Only applies when configured via `build.yaml`; has no effect when set on + /// [JsonSerializable] annotations in source code. + final FieldRename? enumFieldRename; + /// 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. @@ -285,6 +292,7 @@ class JsonSerializable { this.disallowUnrecognizedKeys, this.explicitToJson, this.fieldRename, + this.enumFieldRename, this.ignoreUnannotated, this.includeIfNull, this.converters, @@ -308,6 +316,7 @@ class JsonSerializable { disallowUnrecognizedKeys: false, explicitToJson: false, fieldRename: FieldRename.none, + enumFieldRename: FieldRename.none, ignoreUnannotated: false, includeIfNull: true, genericArgumentFactories: false, @@ -329,6 +338,7 @@ class JsonSerializable { disallowUnrecognizedKeys ?? defaults.disallowUnrecognizedKeys, explicitToJson: explicitToJson ?? defaults.explicitToJson, fieldRename: fieldRename ?? defaults.fieldRename, + enumFieldRename: enumFieldRename ?? defaults.enumFieldRename, ignoreUnannotated: ignoreUnannotated ?? defaults.ignoreUnannotated, includeIfNull: includeIfNull ?? defaults.includeIfNull, genericArgumentFactories: diff --git a/json_annotation/lib/src/json_serializable.g.dart b/json_annotation/lib/src/json_serializable.g.dart index 6e5139b6..09589f4c 100644 --- a/json_annotation/lib/src/json_serializable.g.dart +++ b/json_annotation/lib/src/json_serializable.g.dart @@ -26,6 +26,7 @@ JsonSerializable _$JsonSerializableFromJson( 'create_to_json', 'date_time_utc', 'disallow_unrecognized_keys', + 'enum_field_rename', 'explicit_to_json', 'field_rename', 'generic_argument_factories', @@ -50,6 +51,10 @@ JsonSerializable _$JsonSerializableFromJson( (v) => v as bool?, ), explicitToJson: $checkedConvert('explicit_to_json', (v) => v as bool?), + enumFieldRename: $checkedConvert( + 'enum_field_rename', + (v) => $enumDecodeNullable(_$FieldRenameEnumMap, v), + ), fieldRename: $checkedConvert( 'field_rename', (v) => $enumDecodeNullable(_$FieldRenameEnumMap, v), @@ -80,6 +85,7 @@ JsonSerializable _$JsonSerializableFromJson( 'createToJson': 'create_to_json', 'disallowUnrecognizedKeys': 'disallow_unrecognized_keys', 'explicitToJson': 'explicit_to_json', + 'enumFieldRename': 'enum_field_rename', 'fieldRename': 'field_rename', 'ignoreUnannotated': 'ignore_unannotated', 'includeIfNull': 'include_if_null', @@ -102,6 +108,7 @@ Map _$JsonSerializableToJson(JsonSerializable instance) => 'create_to_json': instance.createToJson, 'date_time_utc': instance.dateTimeUtc, 'disallow_unrecognized_keys': instance.disallowUnrecognizedKeys, + 'enum_field_rename': _$FieldRenameEnumMap[instance.enumFieldRename], 'explicit_to_json': instance.explicitToJson, 'field_rename': _$FieldRenameEnumMap[instance.fieldRename], 'generic_argument_factories': instance.genericArgumentFactories, diff --git a/json_serializable/CHANGELOG.md b/json_serializable/CHANGELOG.md index fd078825..2be661a3 100644 --- a/json_serializable/CHANGELOG.md +++ b/json_serializable/CHANGELOG.md @@ -1,5 +1,7 @@ ## 6.13.0-wip +- Add `enum_field_rename` `build.yaml` configuration option. + ([#1556](https://github.com/google/json_serializable.dart/pull/1556)) - Fix schema generation for many different types of fields. ([#1549](https://github.com/google/json_serializable.dart/issues/1549)) - Support `JsonSerializable.dateTimeUtc` configuration option. diff --git a/json_serializable/README.md b/json_serializable/README.md index 29db530a..0333450e 100644 --- a/json_serializable/README.md +++ b/json_serializable/README.md @@ -322,6 +322,7 @@ targets: date_time_utc: false disallow_unrecognized_keys: false explicit_to_json: false + enum_field_rename: none field_rename: none generic_argument_factories: false ignore_unannotated: false diff --git a/json_serializable/lib/src/encoder_helper.dart b/json_serializable/lib/src/encoder_helper.dart index fa3f1369..f8840695 100644 --- a/json_serializable/lib/src/encoder_helper.dart +++ b/json_serializable/lib/src/encoder_helper.dart @@ -174,7 +174,10 @@ mixin EncodeHelper implements HelperCore { // We can consider enums as kinda like having custom converters // same rules apply. If `null` is in the set of encoded values, we // should not write naive - final enumWithNullValue = enumFieldWithNullInEncodeMap(field.type); + final enumWithNullValue = enumFieldWithNullInEncodeMap( + field.type, + defaultEnumFieldRename: config.enumFieldRename, + ); if (enumWithNullValue != null) { return !enumWithNullValue; } diff --git a/json_serializable/lib/src/enum_utils.dart b/json_serializable/lib/src/enum_utils.dart index 8fc15ab2..bca73be2 100644 --- a/json_serializable/lib/src/enum_utils.dart +++ b/json_serializable/lib/src/enum_utils.dart @@ -5,6 +5,7 @@ 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 'package:source_helper/source_helper.dart'; @@ -19,8 +20,14 @@ String constMapName(DartType targetType) => /// /// Otherwise, returns `true` if [targetType] is nullable OR if one of the /// encoded values of the enum is `null`. -bool? enumFieldWithNullInEncodeMap(DartType targetType) { - final enumMap = _enumMap(targetType); +bool? enumFieldWithNullInEncodeMap( + DartType targetType, { + FieldRename? defaultEnumFieldRename, +}) { + final enumMap = _enumMap( + targetType, + defaultEnumFieldRename: defaultEnumFieldRename, + ); if (enumMap == null) return null; @@ -34,10 +41,12 @@ bool? enumFieldWithNullInEncodeMap(DartType targetType) { String? enumValueMapFromType( DartType targetType, { bool nullWithNoAnnotation = false, + required FieldRename? defaultEnumFieldRename, }) { final enumMap = _enumMap( targetType, nullWithNoAnnotation: nullWithNoAnnotation, + defaultEnumFieldRename: defaultEnumFieldRename, ); if (enumMap == null) return null; @@ -56,6 +65,7 @@ String? enumValueMapFromType( Map? _enumMap( DartType targetType, { bool nullWithNoAnnotation = false, + required FieldRename? defaultEnumFieldRename, }) { final targetTypeElement = targetType.element; if (targetTypeElement == null) return null; @@ -68,12 +78,20 @@ Map? _enumMap( return null; } + if (jsonEnum.valueField != null && jsonEnum.fieldRename != FieldRename.none) { + log.warning( + '`JsonEnum.fieldRename` is ignored when `valueField` is set. ' + 'Enum values are derived from the `${jsonEnum.valueField}` field.', + ); + } + return { for (var field in enumFields) field: _generateEntry( field: field, jsonEnum: jsonEnum, targetType: targetType, + defaultEnumFieldRename: defaultEnumFieldRename, ), }; } @@ -82,6 +100,7 @@ Object? _generateEntry({ required FieldElement field, required JsonEnum jsonEnum, required DartType targetType, + required FieldRename? defaultEnumFieldRename, }) { final annotation = const TypeChecker.typeNamed( JsonValue, @@ -91,8 +110,6 @@ Object? _generateEntry({ if (annotation == null) { final valueField = jsonEnum.valueField; if (valueField != null) { - // TODO: fieldRename is pointless here!!! At least log a warning! - final fieldElementType = field.type.element as EnumElement; final e = fieldElementType.getField(valueField); @@ -125,7 +142,10 @@ Object? _generateEntry({ ); } } else { - return encodedFieldName(jsonEnum.fieldRename, field.name!); + final effectiveRename = jsonEnum.fieldRename != FieldRename.none + ? jsonEnum.fieldRename + : (defaultEnumFieldRename ?? FieldRename.none); + return encodedFieldName(effectiveRename, field.name!); } } else { final reader = ConstantReader(annotation); diff --git a/json_serializable/lib/src/json_enum_generator.dart b/json_serializable/lib/src/json_enum_generator.dart index e69e4cca..5cbae210 100644 --- a/json_serializable/lib/src/json_enum_generator.dart +++ b/json_serializable/lib/src/json_enum_generator.dart @@ -8,9 +8,12 @@ import 'package:json_annotation/json_annotation.dart'; import 'package:source_gen/source_gen.dart'; import 'enum_utils.dart'; +import 'settings.dart'; class JsonEnumGenerator extends GeneratorForAnnotation { - const JsonEnumGenerator() : super(inPackage: 'json_annotation'); + JsonEnumGenerator(this._settings) : super(inPackage: 'json_annotation'); + + final Settings _settings; @override List generateForAnnotatedElement( @@ -28,6 +31,7 @@ class JsonEnumGenerator extends GeneratorForAnnotation { final value = enumValueMapFromType( element.thisType, nullWithNoAnnotation: true, + defaultEnumFieldRename: _settings.config.enumFieldRename, ); return [?value]; diff --git a/json_serializable/lib/src/json_part_builder.dart b/json_serializable/lib/src/json_part_builder.dart index 53ad3f03..f84d5c29 100644 --- a/json_serializable/lib/src/json_part_builder.dart +++ b/json_serializable/lib/src/json_part_builder.dart @@ -29,7 +29,7 @@ Builder jsonPartBuilder({ [ _UnifiedGenerator([ JsonSerializableGenerator.fromSettings(settings), - const JsonEnumGenerator(), + JsonEnumGenerator(settings), ]), const JsonLiteralGenerator(), ], diff --git a/json_serializable/lib/src/settings.dart b/json_serializable/lib/src/settings.dart index a372d188..e996f99a 100644 --- a/json_serializable/lib/src/settings.dart +++ b/json_serializable/lib/src/settings.dart @@ -52,7 +52,7 @@ class Settings { /// If [typeHelpers] is not provided, the built-in helpers are used: /// [BigIntHelper], [DateTimeHelper], [DurationHelper], [JsonHelper], and /// [UriHelper]. - Settings({required JsonSerializable? config, List? typeHelpers}) + Settings({JsonSerializable? config, List? typeHelpers}) : config = config != null ? ClassConfig.fromJsonSerializable(config) : ClassConfig.defaults, diff --git a/json_serializable/lib/src/type_helpers/config_types.dart b/json_serializable/lib/src/type_helpers/config_types.dart index 439454b7..c5a1ce0b 100644 --- a/json_serializable/lib/src/type_helpers/config_types.dart +++ b/json_serializable/lib/src/type_helpers/config_types.dart @@ -65,6 +65,7 @@ class ClassConfig { final bool disallowUnrecognizedKeys; final bool explicitToJson; final FieldRename fieldRename; + final FieldRename enumFieldRename; final bool genericArgumentFactories; final bool ignoreUnannotated; final bool includeIfNull; @@ -85,6 +86,7 @@ class ClassConfig { required this.disallowUnrecognizedKeys, required this.explicitToJson, required this.fieldRename, + required this.enumFieldRename, required this.genericArgumentFactories, required this.ignoreUnannotated, required this.includeIfNull, @@ -121,6 +123,8 @@ class ClassConfig { config.genericArgumentFactories ?? ClassConfig.defaults.genericArgumentFactories, fieldRename: config.fieldRename ?? ClassConfig.defaults.fieldRename, + enumFieldRename: + config.enumFieldRename ?? ClassConfig.defaults.enumFieldRename, disallowUnrecognizedKeys: config.disallowUnrecognizedKeys ?? ClassConfig.defaults.disallowUnrecognizedKeys, @@ -142,6 +146,7 @@ class ClassConfig { disallowUnrecognizedKeys: false, explicitToJson: false, fieldRename: FieldRename.none, + enumFieldRename: FieldRename.none, genericArgumentFactories: false, ignoreUnannotated: false, includeIfNull: true, @@ -162,6 +167,7 @@ class ClassConfig { includeIfNull: includeIfNull, genericArgumentFactories: genericArgumentFactories, fieldRename: fieldRename, + enumFieldRename: enumFieldRename, disallowUnrecognizedKeys: disallowUnrecognizedKeys, dateTimeUtc: dateTimeUtc, // TODO typeConverters = [] @@ -180,6 +186,7 @@ class ClassConfig { createJsonSchema: createJsonSchema, dateTimeUtc: dateTimeUtc, disallowUnrecognizedKeys: disallowUnrecognizedKeys, + enumFieldRename: enumFieldRename, explicitToJson: explicitToJson, fieldRename: fieldRename, genericArgumentFactories: genericArgumentFactories, diff --git a/json_serializable/lib/src/type_helpers/enum_helper.dart b/json_serializable/lib/src/type_helpers/enum_helper.dart index ce7641fd..39db99fd 100644 --- a/json_serializable/lib/src/type_helpers/enum_helper.dart +++ b/json_serializable/lib/src/type_helpers/enum_helper.dart @@ -21,7 +21,10 @@ class EnumHelper extends TypeHelper { String expression, TypeHelperContextWithConfig context, ) { - final memberContent = enumValueMapFromType(targetType); + final memberContent = enumValueMapFromType( + targetType, + defaultEnumFieldRename: context.config.enumFieldRename, + ); if (memberContent == null) { return null; @@ -30,7 +33,11 @@ class EnumHelper extends TypeHelper { context.addMember(memberContent); if (targetType.isNullableType || - enumFieldWithNullInEncodeMap(targetType) == true) { + enumFieldWithNullInEncodeMap( + targetType, + defaultEnumFieldRename: context.config.enumFieldRename, + ) == + true) { return '${constMapName(targetType)}[$expression]'; } else { return '${constMapName(targetType)}[$expression]!'; @@ -44,7 +51,10 @@ class EnumHelper extends TypeHelper { TypeHelperContextWithConfig context, bool defaultProvided, ) { - final memberContent = enumValueMapFromType(targetType); + final memberContent = enumValueMapFromType( + targetType, + defaultEnumFieldRename: context.config.enumFieldRename, + ); if (memberContent == null) { return null; diff --git a/json_serializable/lib/src/utils.dart b/json_serializable/lib/src/utils.dart index 3d28f768..7b58e686 100644 --- a/json_serializable/lib/src/utils.dart +++ b/json_serializable/lib/src/utils.dart @@ -121,6 +121,7 @@ ClassConfig mergeConfig( annotation.disallowUnrecognizedKeys ?? config.disallowUnrecognizedKeys, explicitToJson: annotation.explicitToJson ?? config.explicitToJson, fieldRename: annotation.fieldRename ?? config.fieldRename, + enumFieldRename: annotation.enumFieldRename ?? config.enumFieldRename, genericArgumentFactories: annotation.genericArgumentFactories ?? (classElement.typeParameters.isNotEmpty && diff --git a/json_serializable/test/config_test.dart b/json_serializable/test/config_test.dart index 0f1c80ec..667a3d2a 100644 --- a/json_serializable/test/config_test.dart +++ b/json_serializable/test/config_test.dart @@ -136,6 +136,9 @@ void main() { String lastLine; lastLine = switch (entry.key) { + 'enum_field_rename' => + '`42` is not one of the supported values: none, kebab, snake, ' + 'pascal, screamingSnake', 'field_rename' => '`42` is not one of the supported values: none, kebab, snake, ' 'pascal, screamingSnake', @@ -178,6 +181,7 @@ const _invalidConfig = { 'create_to_json': 42, 'date_time_utc': 42, 'disallow_unrecognized_keys': 42, + 'enum_field_rename': 42, 'explicit_to_json': 42, 'field_rename': 42, 'generic_argument_factories': 42, diff --git a/json_serializable/test/json_serializable_test.dart b/json_serializable/test/json_serializable_test.dart index da64a70d..5966a4a4 100644 --- a/json_serializable/test/json_serializable_test.dart +++ b/json_serializable/test/json_serializable_test.dart @@ -5,7 +5,9 @@ @TestOn('vm') library; +import 'package:json_annotation/json_annotation.dart'; import 'package:json_serializable/json_serializable.dart'; +import 'package:json_serializable/src/settings.dart'; import 'package:path/path.dart' as p; import 'package:source_gen_test/source_gen_test.dart'; import 'package:test/test.dart'; @@ -36,12 +38,12 @@ Future main() async { final jsonEnumTestReader = await initializeLibraryReaderForDirectory( p.join('test', 'src'), - '_json_enum_test_input.dart', + '_enum_default_test_input.dart', ); testAnnotatedElements( jsonEnumTestReader, - const JsonEnumGenerator(), + JsonEnumGenerator(Settings()), expectedAnnotatedTests: { 'EnumValueIssue1147', 'EnumValueNotAField', @@ -50,6 +52,50 @@ Future main() async { 'UnsupportedClass', }, ); + + final enumDefaultRenameReader = await initializeLibraryReaderForDirectory( + p.join('test', 'src'), + '_enum_rename_test_input.dart', + ); + + testAnnotatedElements( + enumDefaultRenameReader, + JsonEnumGenerator(Settings()), + expectedAnnotatedTests: {'EnumForDefaultRename', 'EnumWithKebabOverride'}, + ); + + final jsonEnumValuefieldFieldrenameWarningReader = + await initializeLibraryReaderForDirectory( + p.join('test', 'src'), + '_enum_snake_test_input.dart', + ); + + testAnnotatedElements( + jsonEnumValuefieldFieldrenameWarningReader, + JsonEnumGenerator( + Settings( + config: const JsonSerializable(enumFieldRename: FieldRename.snake), + ), + ), + expectedAnnotatedTests: { + 'EnumWithJsonConfigThatSetsTheOutput', + 'EnumWithValueFieldAndFieldRename', + }, + ); + + final jsonSerializableEnumConfigTestReader = + await initializeLibraryReaderForDirectory( + p.join('test', 'src'), + '_enum_json_serializable_snake_test_input.dart', + ); + + testAnnotatedElements( + jsonSerializableEnumConfigTestReader, + JsonSerializableGenerator( + config: const JsonSerializable(enumFieldRename: FieldRename.snake), + ), + expectedAnnotatedTests: {'JsonSerialWithEnum'}, + ); } const _expectedAnnotatedTests = { diff --git a/json_serializable/test/shared_config.dart b/json_serializable/test/shared_config.dart index 0f5138ed..6a95804e 100644 --- a/json_serializable/test/shared_config.dart +++ b/json_serializable/test/shared_config.dart @@ -5,7 +5,9 @@ import 'package:json_annotation/json_annotation.dart'; import 'package:json_serializable/src/type_helpers/config_types.dart'; -final jsonSerializableFields = generatorConfigDefaultJson.keys.toList(); +final jsonSerializableFields = generatorConfigDefaultJson.keys + .where((key) => key != 'enum_field_rename') + .toList(); final generatorConfigDefaultJson = Map.unmodifiable( ClassConfig.defaults.toJsonSerializable().toJson(), @@ -26,6 +28,7 @@ final generatorConfigNonDefaultJson = Map.unmodifiable( dateTimeUtc: true, disallowUnrecognizedKeys: true, explicitToJson: true, + enumFieldRename: FieldRename.pascal, fieldRename: FieldRename.kebab, genericArgumentFactories: true, ignoreUnannotated: true, diff --git a/json_serializable/test/src/_json_enum_test_input.dart b/json_serializable/test/src/_enum_default_test_input.dart similarity index 100% rename from json_serializable/test/src/_json_enum_test_input.dart rename to json_serializable/test/src/_enum_default_test_input.dart diff --git a/json_serializable/test/src/_enum_json_serializable_snake_test_input.dart b/json_serializable/test/src/_enum_json_serializable_snake_test_input.dart new file mode 100644 index 00000000..2baedfc9 --- /dev/null +++ b/json_serializable/test/src/_enum_json_serializable_snake_test_input.dart @@ -0,0 +1,31 @@ +// Copyright (c) 2025, 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:source_gen_test/annotations.dart'; + +@ShouldGenerate(r''' +JsonSerialWithEnum _$JsonSerialWithEnumFromJson(Map json) => + JsonSerialWithEnum( + $enumDecode(_$EnumForJsonSerialEnumMap, json['enumValue']), + ); + +Map _$JsonSerialWithEnumToJson(JsonSerialWithEnum instance) => + { + 'enumValue': _$EnumForJsonSerialEnumMap[instance.enumValue]!, + }; + +const _$EnumForJsonSerialEnumMap = { + EnumForJsonSerial.aFunkyName: 'a_funky_name', + EnumForJsonSerial.anotherFunkyName: 'another_funky_name', +}; +''') +@JsonSerializable() +class JsonSerialWithEnum { + final EnumForJsonSerial enumValue; + + JsonSerialWithEnum(this.enumValue); +} + +enum EnumForJsonSerial { aFunkyName, anotherFunkyName } diff --git a/json_serializable/test/src/_enum_rename_test_input.dart b/json_serializable/test/src/_enum_rename_test_input.dart new file mode 100644 index 00000000..49d2c3e6 --- /dev/null +++ b/json_serializable/test/src/_enum_rename_test_input.dart @@ -0,0 +1,29 @@ +// Copyright (c) 2025, 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:source_gen_test/annotations.dart'; + +/// Enum with no fieldRename - used to test that build config enum_field_rename +/// is applied when set (e.g. pascal) and that default is none. +@ShouldGenerate(r''' +const _$EnumForDefaultRenameEnumMap = { + EnumForDefaultRename.firstValue: 'firstValue', + EnumForDefaultRename.secondValue: 'secondValue', + EnumForDefaultRename.thirdValue: 'thirdValue', +}; +''') +@JsonEnum(alwaysCreate: true) +enum EnumForDefaultRename { firstValue, secondValue, thirdValue } + +/// Enum with explicit fieldRename: kebab - used to test that annotation +/// overrides build config (e.g. config pascal should still yield kebab here). +@ShouldGenerate(r''' +const _$EnumWithKebabOverrideEnumMap = { + EnumWithKebabOverride.fooBar: 'foo-bar', + EnumWithKebabOverride.bazQux: 'baz-qux', +}; +''') +@JsonEnum(alwaysCreate: true, fieldRename: FieldRename.kebab) +enum EnumWithKebabOverride { fooBar, bazQux } diff --git a/json_serializable/test/src/_enum_snake_test_input.dart b/json_serializable/test/src/_enum_snake_test_input.dart new file mode 100644 index 00000000..b36522e8 --- /dev/null +++ b/json_serializable/test/src/_enum_snake_test_input.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2025, 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:source_gen_test/annotations.dart'; + +/// Enum with both valueField and fieldRename - used to test that a warning +/// is logged when fieldRename is ignored. +@ShouldGenerate( + r''' +const _$EnumWithValueFieldAndFieldRenameEnumMap = { + EnumWithValueFieldAndFieldRename.success: 200, + EnumWithValueFieldAndFieldRename.error: 500, +}; +''', + expectedLogItems: [ + '`JsonEnum.fieldRename` is ignored when `valueField` is set. ' + 'Enum values are derived from the `code` field.', + ], +) +@JsonEnum( + alwaysCreate: true, + valueField: 'code', + fieldRename: FieldRename.kebab, +) +enum EnumWithValueFieldAndFieldRename { + success(200), + error(500); + + const EnumWithValueFieldAndFieldRename(this.code); + + final int code; +} + +@ShouldGenerate(r''' +const _$EnumWithJsonConfigThatSetsTheOutputEnumMap = { + EnumWithJsonConfigThatSetsTheOutput.aFunkyName: 'a_funky_name', + EnumWithJsonConfigThatSetsTheOutput.anotherFunkyName: 'another_funky_name', +}; +''') +@JsonEnum(alwaysCreate: true) +enum EnumWithJsonConfigThatSetsTheOutput { aFunkyName, anotherFunkyName } diff --git a/json_serializable/tool/readme/readme_template.md b/json_serializable/tool/readme/readme_template.md index ed8750bf..d492ad57 100644 --- a/json_serializable/tool/readme/readme_template.md +++ b/json_serializable/tool/readme/readme_template.md @@ -179,6 +179,7 @@ targets: date_time_utc: false disallow_unrecognized_keys: false explicit_to_json: false + enum_field_rename: none field_rename: none generic_argument_factories: false ignore_unannotated: false