Hemal Moradiya
Hemal Moradiya

Reputation: 2097

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?

Upvotes: 4

Views: 2562

Answers (4)

Iliya Mirzaei
Iliya Mirzaei

Reputation: 166

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

Upvotes: 4

Naman R.
Naman R.

Reputation: 168

Please use this @JsonSerializable(fieldRename: FieldRename.snake) for snake_case convention

For Example

@freezed
class City with _$City {
  @JsonSerializable(fieldRename: FieldRename.snake)
  const factory City({
    required int id,
    required String name,
    required int stateId,
    required String stateName,
  }) = _City;

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

Upvotes: 1

1housand
1housand

Reputation: 606

Are you talking about FieldRename.snake?

import 'package:freezed_annotation/freezed_annotation.dart';

part 'event.freezed.dart';
part 'event.g.dart';

@freezed
class Event with _$Event {
  const Event._();

  @DocumentReferenceJsonConverter()
  @JsonSerializable(
    fieldRename: FieldRename.snake, // <---
  )
  factory Event({
    DocumentReference? reference, // reference
    String? eventTitle, // event_title
    String? eventDescription, // event_description
    String? eventLocation, // event_location
  }) = _Event;
}

json_annotation library documentation

Upvotes: 4

Arnas
Arnas

Reputation: 832

Json to Dart Model can automate JSON conversion to Freezed data class.

Upvotes: 0

Related Questions