Home > Enterprise >  How to delegate a call to a method in json_serialization?
How to delegate a call to a method in json_serialization?

Time:03-16

I've two classes Foo and Bar:

@JsonSerializable()
class Foo {
  final Bar bar;
  Foo(this.bar);

  factory Foo.fromJson(Map<String, dynamic> json) => _$FooFromJson(json);
  Map<String, dynamic> toJson() => _$FooToJson(this);
}

@JsonSerializable()
class Bar {
  final String s;
  Bar(this.s);

  factory Bar.fromJson(Map<String, dynamic> json) => _$BarFromJson(json);
  Map<String, dynamic> toJson() => _$BarToJson(this);
}

Once the code is generated, I use:

final bar = Bar('hi');
final foo = Foo(bar);
print(foo.toJson());

The above line prints

{bar: Instance of 'Bar'}

but I want it to print

{bar: "hi"}

The one way is to override toString method in the Bar class but I don't think it's a good way when using json_serializable for code generation. I think there's trivial property I am missing.

CodePudding user response:

For having custom class inside another class you need to use explicitToJson: true in your target class.

@JsonSerializable(explicitToJson: true)
class Foo {
  final Bar bar;
  Foo(this.bar);

  factory Foo.fromJson(Map<String, dynamic> json) => _$FooFromJson(json);
  Map<String, dynamic> toJson() => _$FooToJson(this);
}
  • Related