[英]How do get values from JSON array that uses a number as indentifier in java?
我正在嘗試解析來自 Web of Trust API 的響應的 JSON。 問題是 API 返回使用整數作為標識符的 JSON,我很難獲得我想要的值。 我正在使用org.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");
謝謝。
這是因為您試圖以字符串的形式訪問列表。 所以:
jsonObj.getString("0")
會為
{"0": "94, 73"}
但不是為了
{"0": [94, 73]}
您需要使用jsonObj.getJSONObject("0")
來獲取該列表。
IN {"0": [1, 2]}
0 標識符具有整數數組,因此只需獲取 Json 數組,如下所示:
JSONArray msg = (JSONArray) json.getJSONObject("google.com").getJSONArray("0");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.