dart-lang / sdk

The Dart SDK, including the VM, dart2js, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
9.95k stars 1.53k forks source link

JsonCodable macro field names #55811

Open hanskokx opened 1 month ago

hanskokx commented 1 month ago

The JsonCodable macro is a colossal step in the right direction, however it lacks an important feature which should be considered. Often, when working with serialized data (in particular, data returned from an API), the field names may differ from the appropriate Dart names. For instance, I've worked with APIs (particularly with Python backends) that would return JSON that looks like this:

{
  "my_value": "some data"
}

When using Freezed or JsonSerializable, I could simply annotate the Dart object as thus:

@freezed
class AccessToken with _$AccessToken {
  const factory AccessToken({
    @JsonKey(name: 'access_token') required String accessToken,
    @JsonKey(name: 'refresh_token') required String refreshToken,
  }) = _AccessToken;

  factory AccessToken.fromJson(Map<String, dynamic> json) =>
      _$AccessTokenFromJson(json);
}

This allows me to map the snake case JSON value to my camel case Dart objects.

jakemac53 commented 1 month ago

Yes, it lacks any configurability at all right now. This is because the metadata introspection APIs for macros are not yet implemented (and we are hashing out the details still).

Once it is well supported, we will certainly add this feature (as well as some other configuration options).

FarisArmoush commented 1 month ago

There is a solution for this when all your data model's keys follow the same naming convention, which is creating a build.yaml folder in the root of your project.

targets:
  $default:
    builders:
      json_serializable:
        options:
          field_rename: snake

It also would be nice if we could configure each model's keys naming convention separately.

jakemac53 commented 1 month ago

@FarisArmoush this issue is about the JsonCodable macro, which is different from the JsonSerializable builder (which is a code generator based on build_runner, not a macro).