JsonCodable macro field names
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.
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).
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.
@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).
any updates about this feature ? Dart 3.5.1 is live and i want to use macros intead of any build_runner libraries.
any updates about this feature ? Dart 3.5.1 is live and i want to use
macrosintead of anybuild_runnerlibraries.
Macros is an experimental unreleased feature provided as an early preview to solicit feedback. You should not rely on it (or any other package which depends on it) in production. It can change, and break and even be entirely removed without any notice. There is no timeline for it.
Sadge. I know that, but i want to use it anyway. Thanks for info btw.