gpt4 book ai didi

java - java中如何从使用数字作为标识符的JSON数组中获取值?

转载 作者:行者123 更新时间:2023-12-01 06:11:36 25 4
gpt4 key购买 nike

我正在尝试解析来自 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") 来获取该列表。

关于java - java中如何从使用数字作为标识符的JSON数组中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33592665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com