Skip to content

Allow null elements in Document#getList #1066

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions bson/src/main/org/bson/Document.java
Original file line number Diff line number Diff line change
Expand Up @@ -392,17 +392,17 @@ public <T> List<T> getList(final Object key, final Class<T> clazz, final List<T>
// A ClassCastException will be thrown if an element in the list is not of type T.
@SuppressWarnings("unchecked")
private <T> List<T> constructValuesList(final Object key, final Class<T> clazz, final List<T> defaultValue) {
List<?> value = get(key, List.class);
List<T> value = get(key, List.class);
if (value == null) {
return defaultValue;
}

for (Object item : value) {
if (!clazz.isAssignableFrom(item.getClass())) {
if (item != null && !clazz.isAssignableFrom(item.getClass())) {
throw new ClassCastException(format("List element cannot be cast to %s", clazz.getName()));
}
}
return (List<T>) value;
return value;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ class DocumentSpecification extends Specification {
when:
Document doc = Document.parse("{x: 1, y: ['two', 'three'], z: [{a: 'one'}, {b:2}], w: {a: ['One', 'Two']}}")
.append('numberList', [10, 20.5d, 30L])
.append('listWithNullElement', [10, null, 20])
List<String> defaultList = ['a', 'b', 'c']

then:
Expand All @@ -84,6 +85,9 @@ class DocumentSpecification extends Specification {
doc.getList('numberList', Number).get(0) == 10
doc.getList('numberList', Number).get(1) == 20.5d
doc.getList('numberList', Number).get(2) == 30L
doc.getList('listWithNullElement', Number).get(0) == 10
doc.getList('listWithNullElement', Number).get(1) == null
doc.getList('listWithNullElement', Number).get(2) == 20
}

def 'should return null list when key is not found'() {
Expand All @@ -103,6 +107,7 @@ class DocumentSpecification extends Specification {
doc.getList('a', String, defaultList) == defaultList
}


def 'should throw an exception when the list elements are not objects of the specified class'() {
given:
Document doc = Document.parse('{x: 1, y: [{a: 1}, {b: 2}], z: [1, 2]}')
Expand Down