来自字符串生成器(Java)的JSON-null错误



我正在使用GET API调用构建一个程序,以便在Eclipse/Java控制台中提取艺术家信息。我与打印JSON的API建立了良好的连接,但在尝试提取特定数据点时出错:无法调用"JSON";org.json.simple.JSONObject.get(Object("因为";nbalbum";为空

我是Java和JSON的新手,所以很欣赏这里的指针。

下面是我的代码,底部有一个JSON返回示例:

public static void main(String[] args) {
{   

}

try {
//scanner for artist name user input in console
Scanner artistscan = new Scanner(System.in); //create scanner
System.out.println("Please enter artist name to search:"); 
String artistname = artistscan.nextLine(); //turn input into string
System.out.println("Here is how many albums this artist has:");
artistscan.close(); 

String oldurl = "https://api.deezer.com/search/artist?q="
+artistname+"";
String newurl=oldurl.replaceAll(" ", "");
URL url = new URL(newurl);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
//Check if connect is made
int responseCode = conn.getResponseCode();
// 200 OK
if (responseCode != 200) {
throw new RuntimeException("HttpResponseCode: " + responseCode);

} else {
StringBuilder informationString = new StringBuilder();

Scanner scanner = new Scanner(url.openStream());

while (scanner.hasNext()) {
informationString.append(scanner.nextLine());
}
//Close the scanner
scanner.close();
//print results
System.out.println(url); //test url is built correctly
System.out.println(informationString);


//Parse JSON results....  
//    error/returns null:
org.json.simple.parser.JSONParser jsonParser = new JSONParser();
org.json.simple.JSONObject jsonObj = new JSONObject();
jsonObj = (JSONObject) jsonParser.parse(String.valueOf(informationString));
JSONObject nbalbum = (JSONObject) jsonObj.get(0);
System.out.println(nbalbum.get("nb_album"));            


}
} catch (Exception e) {
e.printStackTrace();
}

System.out.println("-------------------------------------");
}}
This is an example JSON return:
{"data":[{"id":566,"name":"Foo Fighters","link":"https://www.deezer.com/artist/566","picture":"https://api.deezer.com/artist/566/image","picture_small":"https://e-cdns-images.dzcdn.net/images/artist/54c324b8651addd8c400de22f9dac5c8/56x56-000000-80-0-0.jpg","picture_medium":"https://e-cdns-images.dzcdn.net/images/artist/54c324b8651addd8c400de22f9dac5c8/250x250-000000-80-0-0.jpg","picture_big":"https://e-cdns-images.dzcdn.net/images/artist/54c324b8651addd8c400de22f9dac5c8/500x500-000000-80-0-0.jpg","picture_xl":"https://e-cdns-images.dzcdn.net/images/artist/54c324b8651addd8c400de22f9dac5c8/1000x1000-000000-80-0-0.jpg","nb_album":37,"nb_fan":4040577,"radio":true,"tracklist":"https://api.deezer.com/artist/566/top?limit=50","type":"artist"}],"total":1}

您得到的JSONObject不是有data字段&对于这个字段,您有JSON数组作为值。因此,如果这是真的,那么可能通过jsonObj.get("data")&那么访问某个位置的值可能会起作用。

最新更新