Mongo Java Driver 3.6.1 - How to parse a json array structured String to BasicDBList

假如想象 提交于 2019-12-11 13:32:40

问题


When I use MongoDB 2.x.x I used (BasicDBList) JSON.parse("[]") to parse the string data to Document array. But the latest MongoDB driver says this is deprecated and the BasicDbObject.parse("") only converts to BasicDBObject.

Here is some code samples I earlier used in 2.x.x Java driver

BasicDbList skuList = (BasicDBList) JSON.parse(skus);

So when I upgraded to 3.6.1, the compiler says this is deprecated. And suggested to use BasicDbObject.parse()

But this only accepts JSON objects structured Strings ...

{ "fruit": "apple"}

... not JSON array formatted Strings.

So, if i have a String like "[\"SKU000001\", \"SKU0000002\", \"SKU0000003\"]" how do I convert to BasicDBList?


回答1:


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:

  1. 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"));
    
  2. 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"));
    


来源:https://stackoverflow.com/questions/49813112/mongo-java-driver-3-6-1-how-to-parse-a-json-array-structured-string-to-basicdb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!