7

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.

4 Answers 4

21

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.

Sign up to request clarification or add additional context in comments.

Comments

8

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

1 Comment

why is the explicit_to_json needed ? Why is the default false ?
2

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(...)

2 Comments

thanks for your reply @boformer, i do understand encode will convert it correctly but what im looking for is a returned map whereas encode returns a json String. the firestore lib that Im using expect the datas to be of Map type, so I will have to use decode again to convert it back to Map type. I think if .g file should use instance.item.toJson() to save us the extra effort.
In that case you probably have to write the serialization code yourself
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.