Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ToJson generated code #570

Closed
rodineijf opened this issue Dec 3, 2019 · 1 comment
Closed

ToJson generated code #570

rodineijf opened this issue Dec 3, 2019 · 1 comment

Comments

@rodineijf
Copy link

Analyzing the generated file in the examples (example.g.dart) I founded this piece of code:

Map<String, dynamic> _$PersonToJson(Person instance) {
  final val = <String, dynamic>{
    'firstName': instance.firstName,
  };

  void writeNotNull(String key, dynamic value) {
    if (value != null) {
      val[key] = value;
    }
  }

  writeNotNull('middleName', instance.middleName);
  val['lastName'] = instance.lastName;
  val['date-of-birth'] = instance.dateOfBirth.toIso8601String();
  val['last-order'] = instance.lastOrder?.toIso8601String();
  val['orders'] = instance.orders; // HERE
  return val;
}

Should Orders be assigned directly? Should they not be assigned iterating and converting to json?

Example:

Map<String, dynamic> _$PersonToJson(Person instance) {
  final val = <String, dynamic>{
    'firstName': instance.firstName,
  };

  void writeNotNull(String key, dynamic value) {
    if (value != null) {
      val[key] = value;
    }
  }

  writeNotNull('middleName', instance.middleName);
  val['lastName'] = instance.lastName;
  val['date-of-birth'] = instance.dateOfBirth.toIso8601String();
  val['last-order'] = instance.lastOrder?.toIso8601String();
  val['orders'] = instance.orders?.map((i) => i.toJson())?.toList();
  return val;
}
@natebosch
Copy link
Member

.toJson() is a method that works "magically" when using jsonEncode in the SDK. When serializing specifically with that encoder it will be called automatically.

You can enable the behavior you are looking for by configuring to enable explicitToJson.

https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonSerializable/explicitToJson.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants