toJson method

dynamic toJson({
  1. dynamic keyToJson(
    1. K
    )?,
  2. dynamic valueToJson(
    1. V
    )?,
})

Returns a serialized version of the Map with keys and values serialized.

Implementation

dynamic toJson({
  dynamic Function(K)? keyToJson,
  dynamic Function(V)? valueToJson,
}) {
  if (_keyType == String && keyToJson == null && valueToJson == null) {
    return this;
  }

  // This implementation is here to support the old decoder behavior
  // this should not be needed if the decoder is updated to not look for a nested
  // map with 'k' and 'v' keys. If that is done the return type can be changed
  // to Map<dynamic, dynamic>.
  if (_keyType != String) {
    return entries.map((e) {
      var serializedKey = keyToJson != null ? keyToJson(e.key) : e.key;
      var serializedValue =
          valueToJson != null ? valueToJson(e.value) : e.value;
      return {'k': serializedKey, 'v': serializedValue};
    }).toList();
  }

  return map((key, value) {
    var serializedKey = keyToJson != null ? keyToJson(key) : key;
    var serializedValue = valueToJson != null ? valueToJson(value) : value;
    return MapEntry(serializedKey, serializedValue);
  });
}