JSON 构造函数显示为未定义

JSON constructor shown as undefined

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

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

使用如下代码:

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));

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

你有没有把它添加到你的构建路径中?

这里解释一下:

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

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));

你把 builder 放在 JSONObject 参数里是错误的......我希望这能奏效......祝一切顺利

在maven项目中,我通过在pom.xml中添加依赖https://mvnrepository.com/artifact/org.json/json修复了它并且它有效,我希望它对你有用