use of org.bson.Transformer in project mongo-java-driver by mongodb.
the class JSONCallbackTest method encodingHooks.
@Test
public void encodingHooks() {
BSON.addDecodingHook(Date.class, new Transformer() {
@Override
public Object transform(final Object o) {
return ((Date) o).getTime();
}
});
try {
Date now = new Date();
Object parsedDate = JSON.parse("{ \"$date\" : " + now.getTime() + "}");
assertEquals(Long.class, parsedDate.getClass());
DBObject doc = (DBObject) JSON.parse("{ date : { \"$date\" : " + now.getTime() + "} }");
assertEquals(Long.class, doc.get("date").getClass());
} finally {
BSON.removeDecodingHooks(Date.class);
}
}
use of org.bson.Transformer in project mongo-java-driver by mongodb.
the class DBObjectCodecTest method testTransformers.
@Test
public void testTransformers() {
try {
collection.save(new BasicDBObject("_id", 1).append("x", 1.1));
assertEquals(Double.class, collection.findOne().get("x").getClass());
BSON.addEncodingHook(Double.class, new Transformer() {
public Object transform(final Object o) {
return o.toString();
}
});
collection.save(new BasicDBObject("_id", 1).append("x", 1.1));
assertEquals(String.class, collection.findOne().get("x").getClass());
BSON.clearAllHooks();
collection.save(new BasicDBObject("_id", 1).append("x", 1.1));
assertEquals(Double.class, collection.findOne().get("x").getClass());
BSON.addDecodingHook(Double.class, new Transformer() {
public Object transform(final Object o) {
return o.toString();
}
});
assertEquals(String.class, collection.findOne().get("x").getClass());
BSON.clearAllHooks();
assertEquals(Double.class, collection.findOne().get("x").getClass());
} finally {
BSON.clearAllHooks();
}
}
Aggregations