Search code examples
flutterjson-serialization

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.


Solution

  • 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.