Serialization of custom token types
It would be nice if the serializer could support serialization of tokens using custom data types, for example:
Car ::= <Engine:Engine>;
Where the Engine
is not a subtype of ASTNode
.
Gson
One way of supporting automatic serialization would be to use Google's gson library to serialize the token object (Gson.toJson(object)
). This way many simple object structures could be automatically serialized.
For example, if the engine object looks like this:
{ "valves": 16, "volume": "5L" }
we would have to add the object type so that the deserializer knows what to do with the token:
{ "type": "my.package.Engine", "value": { ... } }
When deserializing, reflection can be used to find the class my.package.Engine
and then the object is deserialized by using Gson.fromJson(json, class)
where class
is the class object for my.package.Engine
.
Here is a small demonstration of serializing a simple object with gson:
import com.google.gson.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
Beta beta = new Beta("X");
beta.children = new Beta[] { new Beta("Y"), new Beta("Z") };
Gson gson = new Gson();
String json = gson.toJson(beta);
System.out.println(json);
Beta unparsed = gson.fromJson(json, Beta.class);
System.out.println(gson.toJson(beta));
System.out.println(gson.toJson(new Date()));
}
}
class Beta {
String name;
Beta[] children = new Beta[0];
Beta(String name) {
this.name = name;
}
}
This gives the following output:
{"name":"X","children":[{"name":"Y","children":[]},{"name":"Z","children":[]}]}
{"name":"X","children":[{"name":"Y","children":[]},{"name":"Z","children":[]}]}
"Mar 20, 2019 2:19:20 PM"
Jackson
I tried to implement the same approach as above using Jackson instead of Gson but it seems that Jackson requires the user to implement custom serialization methods on all the objects that will be serialized.
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws JsonProcessingException, IOException {
Beta beta = new Beta("X");
beta.children = new Beta[] { new Beta("Y"), new Beta("Z") };
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(beta);
System.out.println(json);
Beta unparsed = mapper.readValue(json, Beta.class);
System.out.println(mapper.writeValueAsString(beta));
System.out.println(mapper.writeValueAsString(new Date()));
}
}
class Beta {
String name;
Beta[] children = new Beta[0];
Beta(String name) {
this.name = name;
}
}
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class Beta and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)