How to use FreezedUnionCase.snake for model class

1.5k views Asked by At

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?

3

There are 3 answers

0
Naman R. On BEST ANSWER

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);
}
0
Arnas On

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

0
1housand On

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