Search code examples
flutterdartjson-serializable

How to use private constructor in json_serializable


I'm using a private constructor in my class, but the code generation fails with

The class Foo has no default constructor.

I'm using latest json_serializable: version i.e. 6.1.5:

@JsonSerializable()
class Foo {
  final int count;
  Foo._(this.count);

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

What am I doing wrong?


Solution

  • You can use @JsonSerializable(constructor: '_') which is introduced in the 4.2.0-dev of the JsonSerializable.

    This will allow you to field to specify an alternative constructor to invoke when creating a fromJson helper.

    For example:

    import 'package:json_annotation/json_annotation.dart';
    
    part 'foo.g.dart';
    
    @JsonSerializable(constructor: '_')
    class Foo {
      final int count;
      Foo._(this.count);
    
      factory Foo.fromJson(Map<String, dynamic> json) => _$FooFromJson(json);
    }
    
    

    Now here, instead of using fromJson like this _$Foo._FromJson(json), use it as _$FooFromJson(json)