Récupérer un sous élément avec TreeNode
Bonjour, j’ignore si je poste au bon endroit, puisque je n’ai pas vu de catégorie traitant du JSON.
Je veux récupérer, dans une page web et affichée en JSON, un sous-élément de la structure.
Le fichier JSON :
Code:
{"responseHeader":{"status":0,"QTime":13,"params":{"echoParams":"all","wt":"json","q":"solrpingquery","distrib":"false"}},"status":"OK"}
Et j’aimerais avoir accès à « QTime ».
Mon code est le suivant :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
public class ServerInfo{
private static ObjectMapper mapper = new ObjectMapper();
public static int testCore(URL url) throws IOException {
int qTime = 0;
URLConnection yc = url.openConnection();
if (yc instanceof HttpURLConnection) {
HttpURLConnection httpConnection = (HttpURLConnection) yc;
// HTTP CODE
int code = httpConnection.getResponseCode();
if (code == 201 || code == 200) {
TreeNode jsonObj = mapper.readTree(httpConnection.getInputStream());
qTime = ((JsonNode) jsonObj.path("responseHeader.QTime")).asInt();
}
}
return qTime;
}
public static int statusCore(String ur_str) throws MalformedURLException {
URL url = new URL(ur_str);
try {
int qTime = ServerInfo.testCore(url);
if (qTime == 0)
throw new Exception("No response!");
return qTime;
} catch (Exception e) {
System.err.println("error - not a http request!");
return 1;
}
}
public static int checkCore(String ur_str) throws MalformedURLException {
int qTime = statusCore(ur_str);
int nullVariable = 2;
int errorVariable = 3;
try{
if (qTime != 1) {
return qTime;
} else {
return nullVariable;
}
}catch (Exception e) {
return errorVariable;
}
}
} |
Le résultat est 1, donc erreur dans la méthode statusCore.
Que pensez-vous ?