【问题标题】:json parsing data from url getting nullpointExceptionjson从url解析数据获取空指针异常
【发布时间】:2017-02-11 09:40:36
【问题描述】:

从 URL-Json 源获取 JSONObject。

   public class source02 {
       public static void main(String[] args) {
          try {
            URL url = new  URL("http://openapi.seoul.go.kr:8088/sample/json/StationDayTrnsitNmpr/1/5/");
            InputStreamReader isr = new InputStreamReader(url.openConnection().getInputStream(), "UTF-8");
            JSONObject object = (JSONObject)JSONValue.parse(isr);

            JSONObject sdt = (JSONObject) object.get("StationDayTrnsitNmpr");
            System.out.println(sdt.get("list_total_count").toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

和Json源

   {"StationDayTrnsitNmpr":{"list_total_count":44,"RESULT":{"CODE":"INFO-000","MESSAGE":"정상 처리되었습니다"},"row":[{"SN":"1","STATN_NM":"신도림","WKDAY":333873.0,"SATDAY":298987.0,"SUNDAY":216886.0},{"SN":"2","STATN_NM":"동대문역사문화공원","WKDAY":251049.0,"SATDAY":211456.0,"SUNDAY":150589.0},{"SN":"3","STATN_NM":"충무로","WKDAY":229882.0,"SATDAY":194865.0,"SUNDAY":142150.0},{"SN":"4","STATN_NM":"종로3가","WKDAY":224539.0,"SATDAY":196606.0,"SUNDAY":142525.0},{"SN":"5","STATN_NM":"사당","WKDAY":200985.0,"SATDAY":180230.0,"SUNDAY":134354.0}]}}

获取 java.lang.NullPointerException 在 api.source02.main(source02.java:16)

【问题讨论】:

  • 第 16 行到底是什么?还要记录 object 以查看它是如何表示的。

标签: java json jsp parsing


【解决方案1】:

这对我有用

        URL url = new URL("http://openapi.seoul.go.kr:8088/sample/json/StationDayTrnsitNmpr/1/5/");
        InputStreamReader isr = new InputStreamReader(url.openConnection().getInputStream(), "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        StringBuilder response = new StringBuilder();
        for (String line = br.readLine(); line != null; line = br.readLine()) {
            response.append(line);
        }
        JSONObject object = new JSONObject(response.toString());
        JSONObject sdt = (JSONObject) object.get("StationDayTrnsitNmpr");
        System.out.println(sdt.get("list_total_count").toString());

【讨论】:

  • 还有一个问题。如何制作“行”json数组列表?如何从 JSonObject sdt 访问“行”?
  • @JakeAvacado 我不明白。你想达到什么目标?
  • @JakeAvacado 这行得通 - System.out.println(sdt.get("row"));
猜你喜欢
  • 2016-05-25
  • 2012-03-30
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多