1

I have a String in Pentaho Data Integration (PDI) a.k.a. Kettle, in a transformation's UDJC step. So using Java, I need to take that String which contains JSON from MongoDB, and put it into a BasicBSONObject. (I can use import statements but I can't install things as part of a solution.)

I got the String into an org.bson.Document so it seems like the hard part's over, but I still can't figure out how to convert one type of bson to another here, resulting in an object of type org.bson.BasicBSONObject

This errors out on the last line:

import org.bson.Document;
...
String mongoResultString = get(Fields.In, "mongoAsset").getString(r);
Document mongoResultDoc = Document.parse(mongoResultString );
BasicBSONObject mongoResult = (BasicBSONObject) mongoResultDoc;

Tried ecosia, google, and searching Stack Overflow. Thanks.

Nathan
  • 65
  • 9

2 Answers2

2

There is a BasicDBObject#parse method in MongoDB Java Driver library, which is most probably present on the classpath of your application. This method, according to the documentation, parses a string in MongoDB Extended JSON format to a BasicDBObject.

You can use it directly and skip the Document parsing step.

BasicBSONObject mongoResult = BasicDBObject.parse(mongoResultString);
Yevgen
  • 1,576
  • 1
  • 15
  • 17
2

After much wasted time with multiple online resources suggesting to use org.bson.Document and then they become too busy being BSON evangelists to mention the actual solution part... facepalm ...I finally found out this is actually quite simple. Parse the String into a JSON and immediately cast to a BasicBSONObject:

BasicBSONObject mongoResult = (BasicBSONObject) com.mongodb.util.JSON.parse(mongoResultString);

That worked for me because I already know mongoResultString is valid JSON because it came straight from Mongo, but otherwise could presumably wrap it in a try block.

Not sure of performance differences or gotchas, but now that I know what to look for, I've also seen evidence of Eugene's solution being workable. (Also shorter. Accepting that as the solution.) Thanks very much!

Nathan
  • 65
  • 9