我想解析來自Web of Trust API的響應JSON。問題是API返回的JSON使用整數作爲標識符,我很難得到我想要的值。我使用org.json:json
如何從JSON數組中獲取使用數字作爲標識符的值?
下面有什麼樣的JSON看起來像一個例子:
{
"google.com": {
"target": "google.com",
"0": [ 94, 73 ],
"1": [ 94, 73 ],
"2": [ 94, 73 ],
"4": [ 93, 66 ],
"categories": {
"501": 99,
"301": 43
}
}
}
我試圖從「0」和「4」獲得的值。
繼承人我使用Java代碼解析它:
package eclipseurlplugin.handlers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonTest {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://api.mywot.com/0.4/public_link_json2?hosts=google.com/&key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
String jsonValue = json.getJSONObject("google.com").getString("0");
System.out.println(jsonValue);
}
}
我嘗試使用下面的代碼來獲取值,但我得到一個異常。是否有捷徑可尋?
String jsonValue = json.getJSONObject("google.com").getString("0");
謝謝。
是什麼,你得到的異常? –
那些不是整數,它們是包含數字的字符串。 –
**安迪所說的** - ***總是***在詢問有關例外情況時包括您得到的例外的全文。 –