Skip to content

Commit 3784566

Browse files
committed
JAVA-743: JSONCallback now applies decoding hooks for all types
1 parent 10d8a0b commit 3784566

File tree

2 files changed

+27
-7
lines changed

2 files changed

+27
-7
lines changed

src/main/com/mongodb/util/JSONCallback.java

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,6 @@ public Object objectDone() {
6363
// override the object if it's a special type
6464
if (b.containsField("$oid")) {
6565
o = new ObjectId((String) b.get("$oid"));
66-
if (!isStackEmpty()) {
67-
gotObjectId(name, (ObjectId) o);
68-
} else {
69-
setRoot(o);
70-
}
71-
return o;
7266
} else if (b.containsField("$date")) {
7367
if (b.get("$date") instanceof Number) {
7468
o = new Date(((Number) b.get("$date")).longValue());
@@ -117,8 +111,9 @@ public Object objectDone() {
117111
}
118112

119113
if (!isStackEmpty()) {
120-
cur().put(name, o);
114+
_put(name, o);
121115
} else {
116+
o = !BSON.hasDecodeHooks() ? o : BSON.applyDecodingHooks( o );
122117
setRoot(o);
123118
}
124119
return o;

src/test/com/mongodb/util/JSONCallbackTest.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package com.mongodb.util;
22

3+
import com.mongodb.DBObject;
34
import com.mongodb.DBRef;
5+
import org.bson.BSON;
6+
import org.bson.Transformer;
47
import org.bson.types.BSONTimestamp;
58
import org.bson.types.Binary;
69
import org.bson.types.ObjectId;
@@ -41,6 +44,28 @@ public void dateParsing() {
4144

4245
}
4346

47+
@org.testng.annotations.Test(groups = {"basic"})
48+
public void encodingHooks() {
49+
BSON.addDecodingHook(Date.class, new Transformer() {
50+
@Override
51+
public Object transform(final Object o) {
52+
return ((Date) o).getTime();
53+
}
54+
});
55+
56+
try {
57+
Date now = new Date();
58+
59+
Object parsedDate = JSON.parse("{ \"$date\" : " + now.getTime() + "}");
60+
assertEquals(Long.class, parsedDate.getClass());
61+
62+
DBObject doc = (DBObject) JSON.parse("{ date : { \"$date\" : " + now.getTime() + "} }");
63+
assertEquals(Long.class, doc.get("date").getClass());
64+
} finally {
65+
BSON.removeDecodingHooks(Date.class);
66+
}
67+
}
68+
4469
@org.testng.annotations.Test(groups = {"basic"})
4570
public void binaryParsing() {
4671
Binary parsedBinary = (Binary) JSON.parse(("{ \"$binary\" : \"YWJjZA==\", \"$type\" : 0 }"));

0 commit comments

Comments
 (0)