Panda World
Panda World

Reputation: 1996

flutter json_serializable tojson does not work properly

Im looking into the Order class example and found that the Item class is not converted to Map.

class Order {
  int count;
  int itemNumber;
  bool isRushed;
  Item item; 
  Map<String, dynamic> toJson() => _$OrderToJson(this);
}

The generated .g file has this:

Map<String, dynamic> _$OrderToJson(Order instance) {
  ...
  writeNotNull('item', instance.item);
  ...
  return val;
}

The item in order map is still of Item type, but Im expecting it to be auto converted to Map as well. the generated .g file should has something like this

writeNotNull('item', instance.item.toJson());

I don't want to manually add this since it will be overwritten when .g file is regenerated. Why is the json_serializable lib not doing such a simple thing, or am I missing something? thanks.

Upvotes: 7

Views: 7029

Answers (4)

Dhaval Kansara
Dhaval Kansara

Reputation: 3884

Please add the below line above your child-level data model class... So it will call in dept toJson method of each model...

@JsonSerializable(explicitToJson: true)

Upvotes: 2

aaronvargas
aaronvargas

Reputation: 14142

For firebase you'll want the any_map option also since the maps from firebase are <dynamic, dynamic> otherwise it will expect <String, dynamic>

Create this file as build.yaml in the root of your flutter project, it doesn't exist by default.

targets:
  $default:
    builders:
      json_serializable:
        options:
          any_map: true
          explicit_to_json: true

Upvotes: 8

Panda World
Panda World

Reputation: 1996

Now I found the solution, just set this in build.yaml

explicit_to_json = true.

and regenerate the .g file. It should convert it to Map for you now.

Upvotes: 21

boformer
boformer

Reputation: 30103

json.encode(...) will attempt to find a toJson() method on the Item class, and serialize the item correctly. There is no need for the generated serialization logic to call toJson().

You just have to make sure that the Item class is also annotated with @JsonSerializable() and implements toJson().


Also, you would never call toJson() manually, instead you pass your order object to json.encode(...)

Upvotes: 2

Related Questions