2

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);
}
SePröbläm
  • 5,142
  • 6
  • 31
  • 45
  • If what you want is immutability, you could use a freezed [https://pub.dev/packages/freezed] class with JsonSerializable. – Thierry Feb 01 '21 at 18:25
  • Looks like it's not possible, no response since September... https://github.com/google/json_serializable.dart/issues/537 – David Gomes Feb 21 '22 at 19:41

1 Answers1

0

Old question, I know, but as this one comes up on top in Google: the library has now been updated to allow you t o 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

Pepijn
  • 383
  • 2
  • 13