【问题标题】:Using JsonReader to read json url使用 JsonReader 读取 json url
【发布时间】:2015-09-28 13:26:22
【问题描述】:

我正在尝试使用 JsonReader! 读取 json url。一旦我打电话给reader.beginArray(),我就会得到:

java.lang.IllegalStateException:应为 BEGIN_ARRAY,但为 STRING。

这是 json 网址:

http://www.metlink.org.nz/stop/nearbystopdata?lat=-41.278407655948&lng=174.77938892631

    @Override
    protected String doInBackground(String... urls) {

        String result = "";
        String url="http://www.metlink.org.nz/stop/nearbystopdata?lat=-41.278407655948&lng=174.77938892631";

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        try {

            HttpResponse response = httpclient.execute(httppost);
            InputStream  in=response.getEntity().getContent();

            JsonReader reader ;

            reader= new JsonReader(new InputStreamReader(in, "UTF-8"));
            reader.setLenient(true);


             try {
                 listData=(ArrayList<DivanData>) readMessagesArray(reader);
             }
             finally {
               reader.close();
             }





        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }


      public ArrayList<DivanData> readMessagesArray(JsonReader reader) throws IOException {
             ArrayList<DivanData> messages = new ArrayList();

             try {
                 reader.beginArray();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             while (reader.hasNext()) {
               messages.add(readMessage(reader));
             }
             reader.endArray();
             return messages;
           }

我做错了什么?

【问题讨论】:

  • metlink.org.nz/stop/nearbystopdata ? lat=-41.278407655948&lng=174.77938892631
  • 我刚刚检查了您的端点,响应不是 JSON,它是一个正文中包含 json 的 html 页面。这就是为什么你知道你正在将一个字符串传递给你的 jsonReader。
  • 您的 url 是网页不是 JSON,请尝试使用 navigator 的 rest 客户端,这是您检查网络服务的最佳方式。
  • 有没有办法从这个json字符串中获取JsonReader

标签: java android json


【解决方案1】:

既然您有包含内容的 html,为什么不尝试使用 jsoup (http://jsoup.org/) 从 html 中获取 json 作为字符串。这真的很简单,需要更少的代码:

    Document d;
    String url="your_url";
    d = Jsoup.connect(url).get();
    Element p = d.select("body p").first(); // fetch from p tag content
    String jsonString = p.text();

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多