Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use FreezedUnionCase.snake for model class

I am using freezed package as a code generator. My response from API as shown below,

first_name, 
last_name, 
etc..,

And I am defining my model class like this,

firstName,
lastName,
etc..,

If I use @JsonKey(name: 'first_name') then it works but I have to write this annotation for every field I have. Is there any way to set it global?

like image 448
Hemal Moradiya Avatar asked Sep 03 '25 03:09

Hemal Moradiya


1 Answers

Someone has already answered the class based solution, however if you are looking for somehow configure it globally, you can do it by adding a build.yaml file to the root of your project and configure it like below:

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

and you set the value based on the json_serialization enum:

/// 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,

  /// Encodes a field named `screamingSnakeCase` with a JSON key
  /// `SCREAMING_SNAKE_CASE`
  screamingSnake,
}
like image 52
Iliya Mirzaei Avatar answered Sep 05 '25 01:09

Iliya Mirzaei