加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

在Java中解析JSON对象数组

发布时间:2020-12-15 02:09:05 所属栏目:Java 来源:网络整理
导读:我正在尝试解析以下 JSON: {"city":{"id":2643743,"name":"London","coord":{"lon":-0.12574,"lat":51.50853},"country":"GB","population":0},"cod":"200","message":0.0456,"cnt":7,"list":[ {"dt":1440504000,"temp": {"day":16.85,"min":14.23,"max":16
我正在尝试解析以下 JSON:

{"city":{"id":2643743,"name":"London","coord":{"lon":-0.12574,"lat":51.50853},"country":"GB","population":0},"cod":"200","message":0.0456,"cnt":7,"list":[

    {"dt":1440504000,"temp":
        {"day":16.85,"min":14.23,"max":16.85,"night":14.23,"eve":16.32,"morn":16.85},"pressure":1013.06,"humidity":79,"weather":[
        {"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":7.36,"deg":172,"clouds":88,"rain":1.09},{"dt":1440504001,"min":10.03,"max":18.15,"humidity":45,"weather":[
        {"id":501,"speed":15.46,{"dt":1440504002,"min":4.73,"max":11.12,"humidity":59,"weather":[
        {"id":502,"speed":17.12,"rain":1.09}]}

我要解析的信息是:“min”,“max”,“humidity”和“speed”.由于这是我第一次解析数组,我不知道如何解析它.在阅读了一些论坛帖子后,我写了下面的代码:

public void filtraOW7days(String contenidoOW) throws ParseException{ 
    JSONParser parser = new JSONParser();
    try{
        Object obj = parser.parse(contenidoOW);
        JSONObject jsonList = (JSONObject) obj;
        JSONArray list = (JSONArray) jsonList.get("list");
        Iterator<String> unitsIterator = list.iterator();
        int i = 0;
        while(unitsIterator.hasNext()){
            Object uJson = unitsIterator.next();
            JSONObject uj = (JSONObject) uJson;
            this.humOWaux[i] =  (long) uj.get("humidity");
            this.windOWaux[i] = (String) uj.get("speed");


            JSONArray slideContent = (JSONArray) uj.get("temp");
            Iterator c = slideContent.iterator();


            while (c.hasNext()) {
                JSONObject slide = (JSONObject) c.next();
                this.tmaxOWaux[i] =(String) slide.get("max"); 
                this.tminOWaux[i] = (String) slide.get("min"); 
            }


            i++;
        }

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

}

字符串contenidoOW是JSON.This代码给我以下错误:

java.lang.NullPointerException at “this.humOWaux[i] = (long)
uj.get(“humidity”);”.

我不明白为什么(至少我不明白为什么),你能帮助我吗?

编辑:我正在使用org.json.simple并且变量的声明是:

private String [] tminOWaux;
private String [] tmaxOWaux;
私人长[] humowaux;
private String [] windOWaux;

谢谢你的时间,真是太棒了!

解决方法

Long humidity=null; // long humidity=0;
if(uj.get("humidity")!=null){
  humidity=Long.valueOf(uj.get("humidity"))
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读