jsonEncode function Null safety

String jsonEncode(
  1. Object? object,
  2. {Object? toEncodable(
    1. Object? nonEncodable

Converts object to a JSON string.

If value contains objects that are not directly encodable to a JSON string (a value that is not a number, boolean, string, null, list or a map with string keys), the toEncodable function is used to convert it to an object that must be directly encodable.

If toEncodable is omitted, it defaults to a function that returns the result of calling .toJson() on the unencodable object.

Shorthand for json.encode. Useful if a local variable shadows the global json constant.


const data = {'text': 'foo', 'value': 2, 'status': false, 'extra': null};
final String jsonString = jsonEncode(data);
print(jsonString); // {"text":"foo","value":2,"status":false,"extra":null}

Example of converting an otherwise unsupported object to a custom JSON format:

class CustomClass {
  final String text;
  final int value;
  CustomClass({required this.text, required this.value});
  CustomClass.fromJson(Map<String, dynamic> json)
      : text = json['text'],
        value = json['value'];

  static Map<String, dynamic> toJson(CustomClass value) =>
      {'text': value.text, 'value': value.value};

void main() {
  final CustomClass cc = CustomClass(text: 'Dart', value: 123);
  final jsonText = jsonEncode({'cc': cc},
      toEncodable: (Object? value) => value is CustomClass
          ? CustomClass.toJson(value)
          : throw UnsupportedError('Cannot convert to JSON: $value'));
  print(jsonText); // {"cc":{"text":"Dart","value":123}}


String jsonEncode(Object? object,
        {Object? toEncodable(Object? nonEncodable)?}) =>
    json.encode(object, toEncodable: toEncodable);