gpt4 book ai didi

java - 尝试在 Java 中搜索 JSON

转载 作者:行者123 更新时间:2023-12-01 16:17:30 24 4
gpt4 key购买 nike

我正在使用 Marvel API 尝试根据用户在搜索框中输入的内容来获取英雄的名字。我非常确定搜索功能有效,因为它将搜索常规数组,但我试图让它通过 JSONArray 进行搜索。以下是我到目前为止所拥有的。

try {
//This is the input stream section. No idea why these need to be here but they are
//in = input
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
//bin = buffered input.... i think.
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
//temp string to hold each line that's read from the reader
String inputLine;

//this keeps adding the lines to the string builder
while ((inputLine = bin.readLine()) != null) {
sb.append(inputLine);
}

//putting the string builder into a json object
JSONObject jsonObject = new JSONObject(sb.toString());

//Checking if the jsonObject has a response inside of it.
//If there is one however it is false then no results are found.

if (jsonObject.has("Response") && jsonObject.getString("Response").equals("False")){
error = true;
} else{
JSONArray results = jsonObject.getJSONArray("name");
}

这是我非常确定有问题的部分,因为我认为它不会进入 JSON 中包含名称的部分。下面是一个示例 JSON,其中的结果是用户搜索单词“captain”时的结果

object      {7}
code : 200
status : Ok
copyright : © 2020 MARVEL
attributionText : Data provided by Marvel. © 2020 MARVEL
attributionHTML : <a href=\"http://marvel.com\">Data provided by Marvel. © 2020 MARVEL</a>
etag : 75d3eb0f8a6fd4ce06372a8e382af0fe85ea966c
data {5}
offset : 0
limit : 10
total : 19
count : 10
results [10]
0 {11}
id : 1009220
name : Captain America
description : Vowing to serve his country any way he could, young Steve Rogers
took the super soldier serum to become America's one-man army. Fighting for the
red, white and blue for over 60 years, Captain America is the living, breathing
symbol of freedom and liberty.
modified : 2020-04-04T19:01:59-0400
thumbnail {2}
resourceURI : http://gateway.marvel.com/v1/public/characters/1009220
comics {4}
series {4}
stories {4}
events {4}
urls [3]
1 {11}
2 {11}
3 {11}
4 {11}
5 {11}
6 {11}
7 {11}
8 {11}
9 {11}

我需要知道为什么它不仅仅将 JSON 的名称部分添加到 JSONArray。目前发生的情况是,当用户搜索某些内容时,尝试这种方式时不会出现任何内容。如有任何帮助,我们将不胜感激。

最佳答案

如果我理解正确的话,name 字段是一个字符串,它是 results 数组的一个元素,而该数组本身就是 >data JSON 对象。要访问 results 数组,请尝试:

JSONArray 结果 = jsonObject.getJSONObject("data").getJSONArray("results")

然后,您可以访问索引i处的单个结果名称,如下所示:

String name_i = results.getJSONObject(i).getString("name")

希望这有帮助。

关于java - 尝试在 Java 中搜索 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62364306/

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