1

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?

Jordi
  • 20,868
  • 39
  • 149
  • 333

2 Answers2

2

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:

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

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.

Vlad Mamaev
  • 565
  • 3
  • 15