Skip to content

unencodable_value_in_to_json

Reports a value in the map a toJson method returns that jsonEncode cannot encode, such as a DateTime. Convert it to a JSON value first.

Tier
advisory
Scope
Dart
Lowest preset
recommended
Fix
none

A value of the map a toJson method returns that jsonEncode cannot encode. The encoder writes numbers, strings, booleans, null, lists, and maps with string keys. It asks any other object for its toJson. The rule reports a value whose static type has none:

  • a DateTime, Duration, Uri, BigInt, RegExp or Set;
  • an enum value whose enum declares no toJson. An extension’s toJson does not count, since the encoder cannot call it.
  • a lazy iterable from an SDK method, such as map or where without toList;
  • a map whose keys cannot be strings;
  • a list or a map whose elements are one of these.

It looks at the map literals the method returns, and at the map and list literals inside them, also under an if or a for. The violation covers the value.

It does not report:

  • in a library that imports a store that takes such values itself: cloud_firestore, hive, hive_ce, isar, sembast;
  • in a class marked by an annotation of json_annotation, freezed_annotation, dart_mappable or built_value;
  • a value of type Object, or of a class without a toJson, since a subtype may have one;
  • a static toJson, or a map from another method.

A store not named above that takes such values is still reported: say so in a justified suppression.

The method compiles and returns a map. It fails only when the map is encoded, often far from the method, with an error that names the value and not the field.

The rule is advisory because a project can give the encoder a toEncodable that handles such values.

Violating
Map<String, Object?> toJson() => {'at': createdAt, 'tags': tags};
Corrected
Map<String, Object?> toJson() =>
{'at': createdAt.toIso8601String(), 'tags': tags.toList()};

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.

Write why on the line directly above the suppression:

// The encoder of this app is given a toEncodable for dates.
// ignore: assay/unencodable_value_in_to_json
'at': createdAt,

// ignore_for_file: assay/unencodable_value_in_to_json silences it in a whole file, and // ignore: unencodable_value_in_to_json without the prefix works too. See Suppressions.