Search in sources :

Example 1 with Transformer

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);
    }
}
Also used : Transformer(org.bson.Transformer) DBObject(com.mongodb.DBObject) DBObject(com.mongodb.DBObject) Date(java.util.Date) Test(org.junit.Test)

Example 2 with Transformer

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();
    }
}
Also used : Transformer(org.bson.Transformer) Test(org.junit.Test)

Aggregations

Transformer (org.bson.Transformer)2 Test (org.junit.Test)2 DBObject (com.mongodb.DBObject)1 Date (java.util.Date)1