related to
https://github.com/RichardHightower/boon/issues/242
https://github.com/RichardHightower/boon/issues/231
Boon JSON: Custom object serializer works with super classes, and interfaces (and example of using HashCodeGuava).
Let's say you want to write a custom object serializer to work with Guava HashCode thingy or whatever else you need.
public static String toJson(Object obj) {
return createSerializer().serialize(obj).toString();
}
private static JsonSerializer createSerializer() {
JsonSerializerFactory factory = new JsonSerializerFactory()
.addTypeSerializer(HashCode.class, new HashCodeSerializer()
);
return factory.create();
}
private static class HashCodeSerializer implements CustomObjectSerializer<HashCode> {
@Override
public Class<HashCode> type() {
return HashCode.class;
}
@Override
public void serializeObject(JsonSerializerInternal serializer, HashCode instance, CharBuf builder) {
serializer.serializeString(instance.toString(), builder);
}
}
You can use it as an object like so:
@Test
public void test() {
Hasher hasher = md5().newHasher();
hasher.putString("heisann", Charset.defaultCharset());
HashCode hash = hasher.hash();
String actualJson = toJson(hash);
ok = actualJson.equals("\"86c7c929d73e1d91c268c9f18d121212\"") || die(actualJson);
puts(actualJson);
}
Or you can use it from a field like so:
The above works now.
It also works for fields.
public static class Employee {
String firstName = "Rick".intern();
HashCode password = md5().newHasher().putString("BACON!", Charset.defaultCharset()).hash();
}
@Test
public void testWithField() {
Employee rick = new Employee();
String actualJson = toJson(rick);
puts(actualJson);
/* Convert it back to an employee. */
Map<String, Object> fromJson = (Map<String, Object>) fromJson(actualJson);
/* Grab the password an convert it into a HashCode. */
String password = idxStr(fromJson, "password");
fromJson = Maps.copy(fromJson);
/* Convert and shove it back into the map. */
idx(fromJson, "password", HashCode.fromString(password));
/* Now convert the map into an Employee. */
Employee rick2 = fromMap(fromJson, Employee.class);
ok = rick.firstName == rick2.firstName.intern() || die();
ok = rick.password.equals(rick2.password) || die(rick2.password);
}
Also...
Example of Using BOON JSON Java, Example of using Guava HashCode, Example of doing custom field conversion in Boon, Example of being awesome. etc.