Skip to content

Possible to 'pass-through' values that are not proper JSON? #669

Closed
@fkettelhoit

Description

@fkettelhoit

I am working with lots of different data classes that need to get serialized to/from Map<String, Object>, which mostly contain serializable data types as values, but also functions and other classes that cannot and should not be converted to/from JSON-compatible types but just 'passed through' as they are (but not ignored either). Since I'm not using the resulting Map as a proper JSON, I don't want the serializer to touch any type that it does not know how to handle but not drop it during a 'serialization' round trip either. Is it possible to do something like this using json_serializable?

I tried to use the following JsonConverter:

class Passthrough<T> implements JsonConverter<T, Object> {
  const Passthrough();

  @override
  T fromJson(Object json) => json as T;

  @override
  Object toJson(T json) => json;
}

typedef SomeFnType = void Function();

@JsonSerializable()
class Foo {
  @JsonKey()
  @Passthrough()
  final SomeFnType someFn;

  Foo(this.someFn);
}

However this causes the build runner to fail (I assume because the resulting type is still not JSON-compatible):

[SEVERE]json_serializable:json_serializable on lib/src/some_file.dart: Could not generate `fromJson` code for `someFn`.
None of the provided `TypeHelper` instances support the defined type.
package:some_package/src/some_file.dart:44:20
   ╷
44 │   final SomeFnType someFn;
   │                    ^^^^^^
   ╵

Is it possible to do this using TypeHelpers? If so, is there any documentation on how to provide custom TypeHelpers?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions