【问题标题】:Unable to parse JSON from url无法从 url 解析 JSON
【发布时间】:2016-04-03 11:58:32
【问题描述】:

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

URL

可以通过更改查询字符串的“标题”部分来生成其他查询。解析 JSON 和提取“See Also”链接的代码应该足够通用,可以用于任何 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 的详细信息以及“See Also”链接? 我以前从未在 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]]"
               }
            ]
         }
      }
   }
}

【问题讨论】:

  • 你调试过应用程序吗??并试图获取 String 变量 `jsonText` 实际包含的内容..
  • 尝试在String jsonText = readAll(rd); 之后打印出jsonText,因为错误提示您的字符串不是以{ 开头,所以您会看到有什么问题
  • 我调试了一下,发现jsonText是空的,不知道是哪里出了问题?
  • 那么另一段代码肯定有问题。请调试并检查整个代码并找到错误本身
  • 不确定为什么要添加 Gson 或 Jackson 标签,因为您没有使用这些标签

标签: java json jakarta-ee jackson gson


【解决方案1】:

如果您仔细阅读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)

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

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

【讨论】:

  • 我无法从 URL 接收字符串,您能否指出为什么会发生这种情况,因为相同的代码适用于其他 ursl 的??
  • 我认为您的URL 可能存在问题,它既没有得到很好的输入数据,也可能因此引发任何异常。或者可能会有更多的事情发生。不能准确地说@user2077648
  • 我已经调试了我的代码,现在数据已被提取,但我仍然无法解析它,
【解决方案2】:

调用json.get("pageid") 时会出现异常org.json.JSONException: JSONObject["pageid"] not found.,因为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。您必须手动解析它。

【讨论】:

  • 是的,你是对的,但是对于这个 json,我怎样才能找到 See Also 值??
猜你喜欢
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多