A utility class for DynamicObject (de)serialization. All of the methods in this class delegate
directly to the static methods in
DynamicObject. The difference is that this class
is instantiable, and can therefore participate in dependency injection. This makes it
straightforward to ensure that types and serialization tags are registered with DynamicObject
before any serialization is attempted.
For example, if you are using
Guice, you can write
a
DynamicObjectSerializer
provider method that registers types:
@Provides
@Singleton
DynamicObjectSerializer getDynamicObjectSerializer() {
DynamicObject.registerTag(Record.class, "recordtag");
DynamicObject.registerType(Identifier.class, new IdentifierTranslator());
return new DynamicObjectSerializer();
}
Classes that need to perform serialization can then have a
DynamicObjectSerializer
injected at construction time:
private final DynamicObjectSerializer serializer;
@Inject
public FlatFileWriter(DynamicObjectSerializer serializer) {
this.serializer = serializer;
}
public void persist(Record rec) throws IOException {
File file = new File("record.txt");
try (
OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
Writer w = new OutputStreamWriter(os, StandardCharsets.UTF_8)
) {
serializer.serialize(rec, w);
}
}