skip to Main Content

In Flutter we do serialization (toJson) of the model, but how can we generate toJson that includes the getters?

Simple example

class MyClass {
  const MyClass({
    required this.a,
    required this.b,
  });
  final double a;
  final double b;

  double get average => (a + b) / 2;
}

We use json_serializable package for generating the toJson method.
It generate the my_class.g.dart file where we have toJson and fromJson methods.
The problem is that in this way we do not have a serialization of the getter (average field in our example).

What can we do to provide the full serialization including class getters?
Is there a way to achieve it using json_serializable, freezed or any other package?

2

Answers


  1. Chosen as BEST ANSWER

    annotate getter with

    @JsonKey(includeToJson: true)
    

    Thanks to @Albert221 answer!

    Full example:

    class MyClass {
      const MyClass({
        required this.a,
        required this.b,
      });
      final double a;
      final double b;
    
      @JsonKey(includeToJson: true)
      double get average => (a + b) / 2;
    }
    

    Explanation:

    In my case adding @JsonKey() only did not work. I had to explicit includeToJson: true


  2. Mark your getter with @JsonKey() annotation. As you can see in the json_serializable source code, it’s meant to be used both for fields and getters:

    @Target({TargetKind.field, TargetKind.getter})
    

    https://pub.dev/documentation/json_annotation/4.8.1/json_annotation/JsonKey-class.html

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search