Home > Back-end >  How to change property names when serializing with dart json_serializable?
How to change property names when serializing with dart json_serializable?

Time:07-18

Here is a json file person.json

{
  "first_name": "John",
  "last_name": "Doe"
}

Here is the Person class

import 'package:json_annotation/json_annotation.dart';

part 'person.g.dart';

@JsonSerializable()
class Person {
  /// The generated code assumes these values exist in JSON.
  final String first_name, last_name;

  /// The generated code below handles if the corresponding JSON value doesn't
  /// exist or is empty.
  final DateTime? dateOfBirth;

  Person({required this.first_name, required this.last_name, this.dateOfBirth});

  /// Connect the generated [_$PersonFromJson] function to the `fromJson`
  /// factory.
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);

  /// Connect the generated [_$PersonToJson] function to the `toJson` method.
  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

Here is how to convert json into the person object.

Person.fromJson(personJson);

The json is using the snake case with underscore, how can I change the snake_case to camelCase when serializing the json? How to change first_name to firstName and last_name to lastName?

CodePudding user response:

From json_serializable's README.md:

To generate to/from JSON code for a class, annotate it with JsonSerializable. You can provide arguments to JsonSerializable to configure the generated code. You can also customize individual fields by annotating them with JsonKey and providing custom arguments.

You should be able to do:


@JsonSerializable()
class Person {
  @JsonKey(name: 'first_name')
  final String firstName;

  @JsonKey(name: 'last_name')
  final String lastName;

  ...
}
  • Related