json_serializable not generating code for final fields and getters

1k Views Asked by At

This is my class:

@JsonSerializable()
class Foo {
  final int a = 0;
  int get b => 42;
}

The generated code doesn't include any of the a or b field:

Foo _$FooFromJson(Map<String, dynamic> json) => Foo();

Map<String, dynamic> _$FooToJson(Foo instance) => <String, dynamic>{};

Note: Please don't write solutions for doing something like Foo(this.a) or Foo() : a = 0 etc. I need to keep my structure as it is.

3

There are 3 best solutions below

0
On

I think since a is final, it is considered a constant and not variable and b is a getter and not a variable, there are no variables (fields) for json_serializable to generate code for.

You need to add a default constructor before json_serializable can run. Since you have no fields, you wil have an empty constructor and empty methods generated.

class Foo {
  final int a = 0;
  int get b => 42;

  const Foo();

  factory Foo.fromJson(Map<String, dynamic> json) => Foo();

  Map<String, dynamic> toJson() => <String, dynamic>{};
}
1
On

Simple answer - this won't be possible as this is done intentionally by design.


If adjusting your model structure is out of the question, you can try manual conversion or a mix of these two.

After encountering the same issues myself, not long ago, I opted in for manual converting my models - and also a combination of two in some cases.

With @JsonSerializable, you can make use of the from/to generated methods, and then in addition, manually convert your final and getter fields.

Another option you can try, at least for the getter fields, is making use of @JsonSerializable(createFactory: false). This will indicate the engine to convert getters as well.

I suggest reading Flutter JSON Docs in detail and figuring out what will suit you the most, depending on your models, what you want, or what you can compromise on.

Worth reading the Github thread on getter conversion.

There's no out of the box workaround for final fields though, but as per this Github thread on final fields, PRs are welcome :)

2
On

If you want easier json parsing, use Dart Data Class Generator extension in VS Code.