MognoDB: JSON util is deprecated

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'}]
  1. There should be quotes around the attribute names.
  2. Quotes should be double quotes (") not single quotes (').

This example is not valid either:

[{'hola': 'adeu'}, {'departament': [{'ambit': 'just', 'name': 'ts'}]}]

References:

2

You 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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like