JSONObject 轉化成 DBObject 的思路是把JSONObject 轉化成String ,再轉換成DBObject 或者BaicDBObject類型
一句話即可:
DBObject userDb = (DBObject) com.mongodb.util.JSON.parse(user
.toString());
示例如下:
import com.mongodb.DBObject; import net.sf.json.JSONObject; //JSONObect 轉化成 DBJONObject public class JSONObjectTotestDBObject { public static void main(String[] rags) { // 一個JSONObject類 JSONObject user = new JSONObject(); user.put("name", "xiaoA"); user.put("age", 12); // 打印該類 System.out.println(user); System.out.println("------------------------"); // 轉化 DBObject userDb = (DBObject) com.mongodb.util.JSON.parse(user .toString()); System.out.print(userDb); } }