java - 无法从 url 解析 JSON

标签 java json jakarta-ee jackson gson

编写一段代码来查询返回 JSON 的 URL,并可以解析 JSON 字符串以提取信息。应该解析和返回的信息是 pageid 和“另请参阅”链接列表。这些链接应该被格式化为实际链接,人们可以使用它来查找适当的文章。 使用维基百科 API 进行查询。示例查询是:

URL

可以通过更改查询字符串的“标题”部分来生成其他查询。解析 JSON 并提取“另请参阅”链接的代码应该足够通用,可以处理任何维基百科文章。

我尝试编写以下代码:

    import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonRead {

    private static String readUrl(String urlString) throws Exception {
        BufferedReader reader = null;
        try {
            URL url = new URL(urlString);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];

            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read); 

            return buffer.toString();
        } finally {
            if (reader != null)
                reader.close();
        }
    }

      public static void main(String[] args) throws IOException, JSONException {
          JSONObject json;
        try {
            json = new JSONObject(readUrl("https://en.wikipedia.org/w/api.php?format=json&action=query&titles=SMALL&prop=revisions&rvprop=content"));
            System.out.println(json.toString());
            System.out.println(json.get("pageid"));

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


          }
}

我在 Eclipse 中使用了以下链接中的 json jar: Json jar

当我运行上面的代码时,我收到以下错误;

org.json.JSONException: JSONObject["pageid"] not found.
at org.json.JSONObject.get(JSONObject.java:471)
at JsonRead.main(JsonRead.java:35)

如何从 URL 中提取 pageid 以及“另请参阅”链接的详细信息? 我以前从未使用过 JSON,因此请让我知道如何继续

json:

    {  
   "batchcomplete":"",
   "query":{  
      "pages":{  
         "1808130":{  
            "pageid":1808130,
            "ns":0,
            "title":"SMALL",
            "revisions":[  
               {  
                  "contentformat":"text/x-wiki",
                  "contentmodel":"wikitext",
                  "*":"{{About|the ALGOL-like programming language|the scripting language formerly named Small|Pawn (scripting language)}}\n\n'''SMALL''', Small Machine Algol Like Language, is a [[computer programming|programming]] [[programming language|language]] developed by Dr. [[Nevil Brownlee]] of [[Auckland University]].\n\n==History==\nThe aim of the language was to enable people to write [[ALGOL]]-like code that ran on a small machine.  It also included the '''string''' type for easier text manipulation.\n\nSMALL was used extensively from about 1980 to 1985 at [[Auckland University]] as a programming teaching aid, and for some internal projects.  Originally written to run on a [[Burroughs Corporation]] B6700 [[Main frame]] in [[Fortran]] IV, subsequently rewritten in SMALL and ported to a DEC [[PDP-10]] Architecture (on the [[Operating System]] [[TOPS-10]]) and IBM S360 Architecture (on the Operating System VM/[[Conversational Monitor System|CMS]]).\n\nAbout 1985, SMALL had some [[Object-oriented programming|object-oriented]] features added to handle structures (that were missing from the early language), and to formalise file manipulation operations.\n\n==See also==\n*[[ALGOL]]\n*[[Lua (programming language)]]\n*[[Squirrel (programming language)]]\n\n==References==\n*[http://www.caida.org/home/seniorstaff/nevil.xml Nevil Brownlee]\n\n[[Category:Algol programming language family]]\n[[Category:Systems programming languages]]\n[[Category:Procedural programming languages]]\n[[Category:Object-oriented programming languages]]\n[[Category:Programming languages created in the 1980s]]"
               }
            ]
         }
      }
   }
}

最佳答案

如果您仔细阅读异常,您会自己找到解决方案。

Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)

您的异常表示A JSONObject文本必须以“{”开头,这意味着您从api收到的json可能不正确.

因此,我建议您调试代码并尝试找出字符串变量 jsonText 中实际收到的内容。

关于java - 无法从 url 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36385113/

相关文章:

java - 我可以在没有 EL 的情况下使用 Hibernate Validator 5 吗?

java - 错误: expected END_ARRAY but was STRING - only on specific phones when using mobile internet

java - 是否可以更改 JSESSIONID cookie 的路径?

java - 如何使用 MyFaces Trinidad 输入日期组件?

maven - 由于处理结构时出现故障,无法在 WildFly 8 上部署 Ear

java - 使用java解析csv文件

java - 删除模式规则中的空格

java - 如何通过AudioTrack播放大型PCM文件? (目前出现错误)

javascript - 循环遍历 Google Sheets JSON

java - NPE 未发生或未被 Servlet 捕获