Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize private fields in json-serializable?

Minimal reproducible code:

@JsonSerializable()
class A {
  final int _x;
  A(int x) : _x = x;

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

Note:

I don't want to make my private field _x public or define a public x getter.

like image 686
iDecode Avatar asked Oct 20 '25 11:10

iDecode


1 Answers

This PR addresses what you want: https://github.com/google/json_serializable.dart/pull/1256/files#diff-0acaf4c472e452d1e5d215a15fcd2266ccd02ab6abdfac0080c2fca845eb9096

You will be able to explicitly set includeFromJson and includeToJson on the private fields you want to include.

Example:

class X {   
  @JsonKey(includeFromJson: true, includeToJson: true)
  int _includeMeToTheJsonParsing;
}

It was merged November 30th. Latest package version is v6.5.4, released at October 25th. So you will need to wait a little bit if you want the official release. Otherwise, you can point directly to the latest commit if you need it ASAP.

like image 191
Gabriel Gava Avatar answered Oct 23 '25 02:10

Gabriel Gava