I am writing a model factory, for which I use JSON to load up a MongoDB DBObject like this:
import com.mongodb.util.JSON;
DBObject dbObject = (DBObject) JSON.parse("{'name':'jack', 'age':30}");
Now, I am trying to break up my JSON files such that I can load up a DBObject with one JSON file, and if needed I can augment the DBObject with another JSON file.
Although it sounds weird, imagine having a set of different type of users. Like, BasicUser, AdvancedUser etc. I c开发者_运维知识库an have a JSON file to load up BasicUser, and put the other non-overlapping details of an AdvancedUser in another JSON file. I can make AdvancedUser extend BasicUser, and so I can just combine the contents of the two JSON files to create an AdvancedUser model.
How could I achieve something like this?
I believe putAll is what you want.
DBObject obj1 = (DBObject) JSON.parse("{'name':'jack', 'age':30}");
DBObject obj2 = (DBObject) JSON.parse("{'role':'admin'}");
obj1.putAll(obj2);
System.out.println(obj1.toString()); //{ "name" : "jack" , "age" : 30 , "role" : "admin"}
I decided to roll out my own function to do this by recursively traversing one DBObject and transferring the contents to another.
精彩评论