简体   繁体   English

使用JsonReader读取json网址

[英]Using JsonReader to read json url

I'm trying to read json url using JsonReader!. 我正在尝试使用JsonReader!读取json url!。 Once I call reader.beginArray() , I get: 调用reader.beginArray() ,我得到:

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING. java.lang.IllegalStateException:预期为BEGIN_ARRAY,但为STRING。

This is the json url : 这是json网址:

http://www.metlink.org.nz/stop/nearbystopdata?lat=-41.278407655948&lng=174.77938892631 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;
           }

What am I doing wrong? 我究竟做错了什么?

Since you have html with content why not try to fetch json as a string from the html using jsoup ( http://jsoup.org/ ). 由于您具有包含内容的html,为什么不尝试使用jsoup( http://jsoup.org/ )从html中获取json作为字符串。 It's really simple and requires less code: 这真的很简单,所需的代码更少:

    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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM