Flutter JSON serializable using json_annotation package how to use JsonConverter with Firebase Firestore DocumentReference
As noted in my answer Are type DocumentReference supported by json_serializable?, due to https://github.com/google/json_serializable.dart/issues/822, you need a nullable document serializer because your type (DocumentReference?) is nullable (because of the ?
at the end).
Quite simply (and you'll need to add @DocumentSerializerNullable() annotation before the class you're trying to use it with).
class DocumentSerializerNullable
implements JsonConverter<DocumentReference?, DocumentReference?> {
const DocumentSerializerNullable();
@override
DocumentReference? fromJson(DocumentReference? docRef) => docRef;
@override
DocumentReference? toJson(DocumentReference? docRef) => docRef;
}
Almog
Software Engineer. #Flutter & #Dart Developer Startup Founder Scuba Diver. Hiker. Lifesaver. Search & Rescue Dog Handler. Blog https://almog.io/blog #flutterdev
Updated on January 03, 2023Comments
-
Almog over 1 year
I'm trying to save a DocumentReference in models using JSON serializable with a custom JsonConverter but not doing it correct
here is my model
@DocumentSerializer() DocumentReference? recentTrainingRef;
My DocumentSerializer Class
class DocumentSerializer implements JsonConverter<DocumentReference, DocumentReference> { const DocumentSerializer(); @override DocumentReference fromJson(DocumentReference docRef) => docRef; @override DocumentReference toJson(DocumentReference docRef) => docRef; }
I'm getting the following error
Could not generate fromJson code for recentTrainingRef.
-
Developer Extraordinare about 2 yearsI'm assuming that DocumentReference is a Firebase class and if so I'm guessing that it's not generating it because DocumentReference probably doesn't have a toJson.
-
Almog about 2 yearsyea but the whole idea is to save the ref in the backend flutter side - pub.dev/documentation/cloud_firestore/latest/cloud_firestore/… Functions side - updateObject.recentTraining = snap.ref; firebase.google.com/docs/reference/js/v8/…
-
Developer Extraordinare about 2 yearsIn that case, you only need the id, right?
-
undershock about 2 years@developerextraordinare - you might need the full path (which yes you could pass as a string as well, but I didn't really like the idea of deserializing arbitrary paths from JSON when they're being stored as a first class format). stackoverflow.com/questions/71022764/…
-