【问题标题】:JSON constructor shown as undefinedJSON 构造函数显示为未定义
【发布时间】:2016-04-20 14:15:53
【问题描述】:

JSONObject 有一个可用的构造函数 JSONObject(String s) 可用,但 eclipse 告诉我它是未定义的。

Documentation

我的代码如下:

URL url = new URL("https://ajax.googleapis.com/ajax/services/search/images?" +"v=1.0&q=barack%20obama&userip=INSERT-USER-IP");

URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer",  "http://google.com");

String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

while((line = reader.readLine()) != null) {
   builder.append(line);
}

JSONObject json = new JSONObject(builder.toString()); //Error, undefined

我已经三重检查了我的所有库都是最新和最稳定的,并且正确实施(除了我的构建路径)。

【问题讨论】:

    标签: java json url connection


    【解决方案1】:

    您是否将其添加到构建路径中?

    解释如下:

    https://stackoverflow.com/a/8997703/3558900

    【讨论】:

    • 我添加了一个不同的库作为库,因此我将其删除并替换为该答案中的库。字符串是 - 我可以实例化 jsonObject 但前提是我通过org.json.JSONObject jsonObject = new org.json.JSONObject(jsonData); 调用它
    • 没关系 - 慢夜,我导入了 org.json.*;它修复了它。
    【解决方案2】:

    我认为这现在应该对你有用.....

    URL url = new URL("https://ajax.googleapis.com/ajax/services/search/images?" +"v=1.0&q=barack%20obama&userip=INSERT-USER-IP");
    
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("Referer",  "http://google.com");
    
    String line;
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    
    while((line = reader.readLine()) != null) {
       builder.append(line);
    }
    
    JSONObject json = new JSONObject(line);
    System.out.println(json.toString(4));
    

    您将构建器放入 JSONObject 参数中是错误的......我希望这应该工作......一切顺利

    【讨论】:

      【解决方案3】:

      使用类似这样的代码:

      static String jsonData;
      File json = new File("JSONFile.json");
      FileReader fr=new FileReader(json);
      BufferedReader br=new BufferedReader(fr);
      StringBuilder sb=  new StringBuilder();
      while((jsonData = br.readLine())!=null)
      {
          sb.append(jsonData);
      }
      jsonData = sb.toString();
      br.close();
      
      JSONObject jsonObject = new JSONObject(jsonData);
      System.out.println(jsonObject.toString(4));
      

      尝试使用此代码,因为我得到了结果。

      【讨论】:

      • 当我尝试实例化 jsonObject 时,Eclipse 仍然给我“构造函数 JSONObject(String) 未定义”。
      【解决方案4】:

      在maven项目中,我通过在pom.xml中添加依赖https://mvnrepository.com/artifact/org.json/json来修复它,它可以工作,希望对你有用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-11
        • 2020-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多