I have a question regarding the json_serializable
package for Flutter.
- Is there any way to check at compile-time if an object is serializable using
json_serializable
? - If not, is there a way to check at runtime if an object is serializable without using reflection?
To provide more context, I want to achieve something similar to checking if a class inherits from another class. However, since json_serializable
works with decorators instead of inheritance, I don’t see a clear way to perform this check.
Here is an example of what I’m trying to do:
import 'package:json_annotation/json_annotation.dart';
part 'example.g.dart';
@JsonSerializable()
class Person {
final String name;
final int age;
Person({required this.name, required this.age});
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
void main() {
var person = Person(name: 'John', age: 30);
// This should compile only if T is serializable
processSerializable(person);
}
// Pseudocode for the generic method I'm trying to implement
void processSerializable<*T extends ...?*>(T object) {
// The implementation should ensure at compile-time that T is serializable
if (isSerializable<T>()) {
print('The object is serializable');
} else {
print('The object is not serializable');
}
}
// How can I implement isSerializable function to perform compile-time check?
Any guidance on how to implement the isSerializable
function to ensure compile-time checks or any alternative approach to ensure that T
is serializable would be greatly appreciated.
Thanks!