Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are type DocumentReference supported by json_serializable?

Tags:

flutter

dart

I'm using json_serializable to generate code. One of my classes has a member variable(legislature) that is of type DocumentReference and when I run the generator I get:

Error running JsonSerializableGenerator
Could not generate `fromJson` code for `legislature`.
None of the provided `TypeHelper` instances support the defined type.

When I remove the legislature the generator works as expected. Are type DocumentReference not supported?

like image 671
flutter Avatar asked Oct 20 '25 04:10

flutter


1 Answers

Not really - the library is pretty explicit that it only expects to support valid JSON types on the output side.

valid JSON type such as String, int, or Map<String, dynamic>.

Source

However there is a workaround. Although DocumentReference is a valid class to pass through to FlutterFire in a Map<String, object?> (particularly in combination with toJson and fromJson arguments to withConverter on DocumentReference or CollectionReference objects, which is probably why you're doing this in the first place!), it is not a valid type for JsonSerializable, which expects only types which can passed directly to json.

A really simple workaround is by extending JsonConverter and creating a customer serializer which you then annotate your class with, eg. by placing a @DocumentSerializer() annotation.

class DocumentSerializer
    implements JsonConverter<DocumentReference, DocumentReference> {
  const DocumentSerializer();

  @override
  DocumentReference fromJson(DocumentReference docRef) => docRef;

  @override
  DocumentReference toJson(DocumentReference docRef) => docRef;
}

This then compiles neatly, provided you've not specified a type to the document reference.

Note that due to https://github.com/google/json_serializable.dart/issues/822 you'll need a seperate class (implements JsonConverter<DocumentReference?, DocumentReference?>) if you want to support `DocumentReference?.

Any classes that you've already annotated with @JsonSerializable() that use the DocumentReference type will also need to be annotated with @DocumentSerializer(), eg.

@JsonSerializable()
@DocumentSerializer()
class MyClass {

DocumentReference myDocRef;

}
like image 114
undershock Avatar answered Oct 23 '25 01:10

undershock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!