【问题标题】:java how to convert a string to net.sf.json.JSONObjectjava如何将字符串转换为net.sf.json.JSONObject
【发布时间】:2014-04-22 01:14:22
【问题描述】:

我收到推文并使用 org.json.simple api 将字符串转换为对象。

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格式的字符串或对象插入到couchdb中

【问题讨论】:

  • 检查你的导入,确保你使用库正确解析json,也就是说如果你使用json.simple,那么最好不要使用net.sf.json.JSONObject object。

标签: java json couchdb


【解决方案1】:

正如错误所说,couchdb 可能使用 net.sf.json.JSONObject。

我在 net.sf.json.JSONObject 中找到了一个用于将字符串转换为 JSON 对象的 API:

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

字符串原因没关系

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

这可能会有帮助。

【讨论】:

    【解决方案2】:

    将 String 转换为 net.sf.json.JSONObject

    JSONObject json = JSONObject.fromObject(str);
    

    【讨论】:

      【解决方案3】:

      如果您的问题是从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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-18
        • 2021-08-01
        • 1970-01-01
        • 2013-06-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多