我有一個(gè) JSON 對(duì)象 obj,我想將它存儲(chǔ)到 MongoDB 中:JSONObject obj = new JSONObject();obj.put("title", obj1.title);//For rules:Map m = new LinkedHashMap();// for rules, first create JSONArray JSONArray ja = new JSONArray(); m = new LinkedHashMap();m.put("right_connective", "&&");m.put("attribute", "amount");m.put("operator", "<=");m.put("value", obj1.amount);m.put("rank", 1);m.put("encapsulated", "false");ja.add(m);m = new LinkedHashMap();m.put("left_connective", "&&");m.put("right_connective", "&&");m.put("attribute", "project");m.put("operator", "==");m.put("value", obj1.project);m.put("rank", 2);m.put("encapsulated", "false");ja.add(m);m = new LinkedHashMap();m.put("left_connective", "&&");m.put("right_connective", "&&");m.put("attribute", "type");m.put("operator", "==");m.put("value", obj1.type);m.put("rank", 3);m.put("encapsulated", "false");ja.add(m);m = new LinkedHashMap();m.put("left_connective", "&&");m.put("attribute", "car");m.put("operator", "==");m.put("value", obj1.car);m.put("rank", 4);m.put("encapsulated", "false");ja.add(m);obj.put("rule", ja);Document doc = Document.parse( obj.toString() );BasicDBObject dbObject = mapper.readValue(obj, BasicDBObject.class);collection.insert(dbObject);我收到“映射器無(wú)法解析為類型”的錯(cuò)誤。我需要包含哪個(gè)導(dǎo)入語(yǔ)句?否則,你能建議替代方法嗎?我不想走 MongoDocument 路線,因?yàn)?insertOne() 函數(shù)在寫(xiě)入數(shù)據(jù)庫(kù)時(shí)跳過(guò)了一些文檔。
2 回答

侃侃爾雅
TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個(gè)贊
如果您正在使用,則不需要映射器org.json.JSONObject:
DBObject object = (DBObject) JSON.parse(obj.toString());
collection.insert(object)

嗶嗶one
TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊
我相信您正在使用如下所示的 jackson.Create ObjectMapper 來(lái)解決“映射器無(wú)法解析為類型”
import com.fasterxml.jackson.databind.ObjectMapper; //import statement
ObjectMapper mapper = new ObjectMapper(); //initialization
添加回答
舉報(bào)
0/150
提交
取消