首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法从url解析JSON

无法从url解析JSON
EN

Stack Overflow用户
提问于 2016-04-03 11:58:32
回答 2查看 2.6K关注 0票数 0

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

URL

还可以生成其他查询,以更改查询字符串的“title”部分。解析JSON并提取“请参阅”链接的代码应该足够通用,可以在维基百科的任何文章中使用。

我试着编写以下代码:

代码语言:javascript
复制
    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:Json罐

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

代码语言:javascript
复制
org.json.JSONException: JSONObject["pageid"] not found.
at org.json.JSONObject.get(JSONObject.java:471)
at JsonRead.main(JsonRead.java:35)

我如何从url中提取页面的细节以及“请参阅”链接?我以前从来没有做过JSON,所以请告诉我如何在这里继续

json:

代码语言:javascript
复制
    {  
   "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]]"
               }
            ]
         }
      }
   }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-04-03 19:12:04

调用json.get("pageid")时会得到异常json.get("pageid"),因为pageid不是根的直接子元素。你必须一直走到目标图上:

代码语言:javascript
复制
int pid = json.getJSONObject("query")
        .getJSONObject("pages")
        .getJSONObject("1808130")
        .getInt("pageid");

如果其中有一个array,那么甚至需要迭代数组元素(或者选择想要的元素)。

编辑这里是获取包含“请参阅”值的字段的代码

代码语言:javascript
复制
String s = json.getJSONObject("query")
        .getJSONObject("pages")
        .getJSONObject("1808130")
        .getJSONArray("revisions")
        .getJSONObject(0)
        .getString("*");

得到的字符串不包含有效的JSON。您必须手动解析它。

票数 1
EN

Stack Overflow用户

发布于 2016-04-03 12:08:21

如果您仔细阅读您的Exception,您将找到您自己的解决方案。

代码语言:javascript
复制
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)

您的ExceptionA JSONObject text must begin with '{',这意味着您从api收到的json可能不正确。

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36385113

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档