【发布时间】:2023-03-22 00:25:02
【问题描述】:
我正在尝试从以下 JSON sn-p 中获取“定义”字符串:
{
"headword": "Google",
"senses": [
{
"definition": [
"a very popular search enginecomputer program that allows you to search for information on the Internet. Google also provides other Internet services including e-mail, maps, social networking, and video sharing."
]
}
],
"datasets": [
"ldoce5",
"dictionary"
],
"id": "cqAFJKTgNJ",
"url": "/v2/dictionaries/entries/cqAFJKTgNJ",
"pronunciations": [
{
"audio": [
{
"lang": "British English",
"type": "pronunciation",
"url": "/v2/dictionaries/assets/ldoce/gb_pron/google1004.mp3"
},
{
"lang": "American English",
"type": "pronunciation",
"url": "/v2/dictionaries/assets/ldoce/us_pron/google1004a.mp3"
}
],
"ipa": "ˈɡuːɡəl"
}
]
}
问题在于,在当前的 JSON sn-p 中,“定义”似乎是一个 JSONObject,每当我尝试将其设为 String 时,都会收到错误消息,指出它不是 String。当我保持原样时,输出包括括号和其他符号:
{"definition":["a very popular search enginecomputer program that allows you to search for information on the Internet. Google also provides other Internet services including e-mail, maps, social networking, and video sharing."]}
有没有办法制作一个漂亮而整洁的字符串,它只包含精确的定义,仅此而已。顺便说一句,使用org.json 库。
代码:
public class MainActivity {
private static String word;
public static void wordInitializer() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
word = reader.readLine();
}
public static void processing() throws Exception {
String path = "http://api.pearson.com/v2/dictionaries/ldoce5/entries?headword=" + word;
URL url = new URL(path);
Scanner scanner = new Scanner(url.openStream());
String line = "";
while (scanner.hasNext())
line += scanner.nextLine();
scanner.close();
JSONObject obj = new JSONObject(line);
JSONObject results = obj.getJSONArray("results").getJSONObject(0);
JSONArray senses = results.getJSONArray("senses");
String definition = senses.getJSONObject(0).toString();
System.out.println(definition);
}
public static void main(String[] args) throws Exception {
wordInitializer();
processing();
}
【问题讨论】:
-
你的代码在哪里
-
这是一个带有单个元素的 JSON 数组,一个 JSON 字符串。请查看 JSON 格式here。
-
定义是json中的一个元素,包含一个数组......