JSONObject
有一个可用的构造函数JSONObject(String s)
可用,但Eclipse告诉我它是未定义的。
文档
我的代码如下:
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
我已经三重检查了我所有的库都是最新和最稳定的,并且正确实现(除了我的构建路径)。
添加到构建路径中?
解释如下:
https://stackoverflow.com/a/8997703/3558900
我认为这现在应该适合您.....
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 参数中是错误的......我希望这应该有效.....万事如意
使用类似下面的代码:
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));
尝试使用此代码,因为我得到了结果。
在 maven 项目中,我通过在 pom 中添加依赖项 https://mvnrepository.com/artifact/org.json/json 来修复它.xml它有效,希望对您有用