json<D> static method

  1. @Deprecated('Use TypeConverter.json2 instead. This converter causes a double JSON ' 'conversion when serializing drift row classes to JSON.')
JsonTypeConverter<D, String> json<D>({
  1. required D fromJson(
    1. dynamic json
    ),
  2. dynamic toJson(
    1. D column
    )?,
  3. JsonCodec json = convert.json,
})

Creates a type converter for storing complex Dart objects in a text column by serializing them as JSON text.

This requires supplying fromJson, a function responsible for mapping the parsed JSON structure to the Dart type D. Optionally, you can also be explicit about the other direction via toJson. By default, Dart's JSON encoder simply calls toJson() on the object.

Finally, the json codec itself can be customized as well if needed.

For sqlite3 databases, jsonb can be used as an alternative encoding for binary columns.

Deprecated

This method is deprecated because it always maps values to Strings when JsonTypeConverter.toJson is called. This is typically undesired behavior, as it leads to double encodings. Consider this table:

class MyValue {
  // ...
  factory MyValue.fromJson(Object? json) {
    // ...
  }

  Object? toJson() => {'foo': 'bar'};
}

class MyTable extends Table {
  TextColumn get col => text().map(TypeConverter.json<MyValue>(
    fromJson: MyValue.fromJson,
  ))();
}

Here, calling MyTableData.toJson will report a value like the following:

{
  "col": "{\"foo\": \"bar\"}"
}

Note that the actual value has been converted to JSON twice. Using TypeConverter.json2 fixes the issue, and will properly encode the value as:

{
  "col": {
    "foo": "bar"
  }
}

Given the different formats, migrating from TypeConverter.json to json2 can be a breaking change.

Implementation

@Deprecated(
  'Use TypeConverter.json2 instead. This converter causes a double JSON '
  'conversion when serializing drift row classes to JSON.',
)
static JsonTypeConverter<D, String> json<D>({
  required D Function(dynamic json) fromJson,
  dynamic Function(D column)? toJson,
  convert.JsonCodec json = convert.json,
}) {
  return _LegacyJsonConverter<D>(
    mapFromJson: fromJson,
    mapToJson: toJson ?? (value) => value,
    json: json,
  );
}