Up to now, I've been using this code in order to create a DBObject from a json string:
DBObject metadataObject = (DBObject)JSON.parse(jsonString);However, com.mongodb.util.JSON is deprecated, and it's recomended to use BasicDBObject.parse instead.
DBObject metadataObject = (DBObject)BasicDBObject.parse(jsonString);Nevertheless, when jsonString is an array (like "[{k: 'v'},{o: 'p'}]" it throws an exception. JSON.parse works fine.
o, What I want to get is using BasicDBObject.parse(...):
(DBObject)JSON.parse("[{'hola': 'adeu'}, {'departament': [{'ambit': 'just', 'name': 'ts'}]}]");code would be (this code crashes):
(DBObject)BasicDBObject.parse("[{'hola': 'adeu'}, {'departament': [{'ambit': 'just', 'name': 'ts'}]}]");Any ideas?
2 Answers
This is not valid JSON:
[{k: 'v'},{o: 'p'}]- There should be quotes around the attribute names.
- Quotes should be double quotes (
") not single quotes (').
This example is not valid either:
[{'hola': 'adeu'}, {'departament': [{'ambit': 'just', 'name': 'ts'}]}]References:
2You can use this,because there is no BasicDBList::parse method
BsonArray parse = BsonArray.parse(json);
BasicDBList dbList = new BasicDBList();
dbList.addAll(parse);
DBObject dbObject = dbList;BasicDBObject.parse(...) is actually for parsing objects, not arrays which are represened by BasicDBList class.