簡體   English   中英

無法從網址解析JSON

[英]Unable to parse JSON from url

編寫一段代碼,查詢返回JSON的URL,並可以解析JSON字符串以提取信息。 應該解析和返回的信息是pageid和“另請參閱”鏈接列表。 這些鏈接應設置為實際鏈接,供個人用來查找適當的文章。 使用Wikipedia API進行查詢。 一個示例查詢是:

網址

可以更改查詢字符串的“標題”部分來生成其他查詢。 解析JSON並提取“另請參閱”鏈接的代碼應足夠通用,以適用於任何Wikipedia文章。

我嘗試編寫以下代碼:

    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您將可以自己找到解決方案。

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)

您的Exception表明A JSONObject text must begin with '{'這意味着您從api接收到的json可能不正確。

因此,我建議您調試代碼並嘗試找出您在String Variable jsonText實際收到的jsonText

您會收到異常org.json.JSONException: JSONObject["pageid"] not found. 調用json.get("pageid")因為pageid不是您的根目錄的直接子元素。 您必須從頭到尾遍歷對象圖:

int pid = json.getJSONObject("query")
        .getJSONObject("pages")
        .getJSONObject("1808130")
        .getInt("pageid");

如果其中有一個array ,則甚至必須迭代數組元素(或選擇所需的數組元素)。

編輯這是獲取包含“另請參閱”值的字段的代碼

String s = json.getJSONObject("query")
        .getJSONObject("pages")
        .getJSONObject("1808130")
        .getJSONArray("revisions")
        .getJSONObject(0)
        .getString("*");

結果字符串不包含有效的JSON。 您將不得不手動解析它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM