2014-04-22 54 views
4

我得到推文並使用org.json.simple api將字符串轉換爲對象。如何將字符串轉換爲net.sf.json.JSONObject

JSONParser jsonParser = new JSONParser(); 
Object json = jsonParser.parse(in); 

,我想用couchdb4j API與obj插入到CouchDB的

Session myDbSession = new Session("localhost",5984) 
    Database myCouchDb = myDbSession.getDatabase("db-name"); 
    Document newdoc = new Document(); 
    Document newdoc = new Document(JSONObject json); 
    myCouchDb.saveDocument(newdoc); 

的錯誤是:

org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject 

如何解決這個問題,或者任何人都可以給出一個解決方案插入一個JSON格式的字符串或對象到沙發數據庫

+2

檢查進口,確保您使用的庫JSON解析正確的,那就是如果你正在使用json.simple,那麼這將是最好不要使用'net.sf. json.JSONObject'對象。 – Jhanvi

回答

1

正如錯誤所述,couchdb可能會使用net.sf .json.JSONObject。

我發現在net.sf.json.JSONObject的API將字符串轉換成JSON對象:

public static JSONObject fromObject(Object object) { return fromObject(object, new JsonConfig()); }

這是一個與字符串OK引起

else if(object instanceof String){ return _fromString((String) object, jsonConfig); }

這可能會有所幫助。

0

如果你的問題是從org.json.simple.Object轉換爲net.sf.json.JSONObject爲什麼不從net.sf.json.JSONObject開始呢?使用你的代碼...

JSONObject json = JSONObject.fromObject(in); 

Session myDbSession = new Session("localhost",5984) 
Database myCouchDb = myDbSession.getDatabase("db-name"); 
Document newdoc = new Document(); 
Document newdoc = new Document(json); 
myCouchDb.saveDocument(newdoc);