Skip to content

Commit 180ada2

Browse files
committed
When encoding a DBObject, if a value implements both Iterable and Map, encode it as a document rather than array. This preserves compatibility with 2.x encoding behavior.
JAVA-1760
1 parent 36f22d1 commit 180ada2

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

driver/src/main/com/mongodb/DBObjectCodec.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,10 +192,10 @@ private void writeValue(final BsonWriter bsonWriter, final EncoderContext encode
192192
bsonWriter.writeNull();
193193
} else if (value instanceof DBRef) {
194194
encodeDBRef(bsonWriter, (DBRef) value);
195-
} else if (value instanceof Iterable) {
196-
encodeIterable(bsonWriter, (Iterable) value);
197195
} else if (value instanceof Map) {
198196
encodeMap(bsonWriter, (Map<String, Object>) value);
197+
} else if (value instanceof Iterable) {
198+
encodeIterable(bsonWriter, (Iterable) value);
199199
} else if (value instanceof BSONObject) {
200200
encodeBsonObject(bsonWriter, ((BSONObject) value));
201201
} else if (value instanceof CodeWScope) {

driver/src/test/functional/com/mongodb/DBObjectCodecTest.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131

3232
import java.util.ArrayList;
3333
import java.util.HashMap;
34+
import java.util.Iterator;
3435
import java.util.List;
3536
import java.util.Map;
3637

@@ -177,4 +178,28 @@ public void shouldEncodedNestedMapsListsAndDocuments() {
177178
.append("lazyDoc", zeroOneBsonDocument)
178179
.append("lazyArray", zeroOneBsonArray), writer.getDocument());
179180
}
181+
182+
@Test
183+
public void shouldEncodeIterableMapAsMap() {
184+
IterableMap iterableMap = new IterableMap();
185+
iterableMap.put("first", 1);
186+
187+
DBObjectCodec dbObjectCodec = new DBObjectCodec(fromProviders(asList(new ValueCodecProvider(), new DBObjectCodecProvider())));
188+
189+
DBObject doc = new BasicDBObject("map", iterableMap);
190+
191+
BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument());
192+
dbObjectCodec.encode(writer, doc, EncoderContext.builder().build());
193+
194+
assertEquals(new BsonDocument("map", new BsonDocument("first", new BsonInt32(1))), writer.getDocument());
195+
}
196+
197+
static class IterableMap extends HashMap<String, Integer> implements Iterable<Integer> {
198+
private static final long serialVersionUID = -5090421898469363392L;
199+
200+
@Override
201+
public Iterator<Integer> iterator() {
202+
return values().iterator();
203+
}
204+
}
180205
}

0 commit comments

Comments
 (0)