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

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

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest