Search code examples
flutterdartjson-deserialization

Flutter/Dart: How do you serialize private variables using json_serializable?


Is there a way to convince Flutter's build runner to include the private variables when serializing/deserializing to/from json? If somehow possible I'd like to avoid making the variables public just because they written to/read from file... How do you handle this?

import 'package:json_annotation/json_annotation.dart';

part 'some_data.g.dart';

@JsonSerializable()
class SomeData {
  double _someVariable;
  double _anotherVariable;

  SomeData();

  factory SomeData.fromJson(Map<String, dynamic> json) => _$SomeDataFromJson(json);

  Map<String, dynamic> toJson() => _$SomeDataToJson(this);
}

Solution

  • Old question, I know, but as this one comes up on top in Google: the library has now been updated to allow you to explicitly mark (private) variables for inclusion using @JsonKey(includeFromJson: true, includeToJson: true).

    import 'package:json_annotation/json_annotation.dart';
    
    part 'some_data.g.dart';
    
    @JsonSerializable()
    class SomeData {
      @JsonKey(includeFromJson: true, includeToJson: true)
      double _someVariable;
      double _anotherVariable;
    
      SomeData();
    
      factory SomeData.fromJson(Map<String, dynamic> json) => _$SomeDataFromJson(json);
    
      Map<String, dynamic> toJson() => _$SomeDataToJson(this);
    }
    

    See also: https://stackoverflow.com/a/74930701/4607142