JSON.parse()
is capable of handling a JSON array, it reads the first character and if it deems the JSON to be an array it handles it accordingly:
case '[':
value = parseArray(name);
break;
BasicDBObject.parse()
expects a valid JSON document so it will throw an exception when given an orphaned JSON array i.e. a JSON array which is not contained in a JSON document.
BasicDBObject.parse()
can handle this ...
{"a": ["SKU000001", "SKU0000002", "SKU0000003"]}
... but it cannot handle this:
["SKU000001", "SKU0000002", "SKU0000003"]
So, there is no direct replacement in the MongoDB v3.x driver for using JSON.parse()
to parse a JSON array. Instead, your options are:
Trick BasicDBObject.parse()
by presenting the JSON array in a valid JSON document, for example:
BasicDBObject basicDBObject = BasicDBObject.parse(String.format("{\"a\": %s}",
"[\"SKU000001\", \"SKU0000002\", \"SKU0000003\"]"));
BasicDBList parsed = (BasicDBList) basicDBObject.get("a");
assertThat(parsed.size(), is(3));
assertThat(parsed, containsInAnyOrder("SKU000001", "SKU0000002", "SKU0000003"));
Use a JSON parsing library to read the JSON array and then use the deserialised result to create a BasicDBList
, for example::
List<String> values = new ObjectMapper().readValue("[\"SKU000001\", \"SKU0000002\", \"SKU0000003\"]",
List.class);
BasicDBList parsed = new BasicDBList();
values.forEach(s -> parsed.add(s));
assertThat(parsed.size(), is(3));
assertThat(parsed, containsInAnyOrder("SKU000001", "SKU0000002", "SKU0000003"));