gpt4 book ai didi

java - Java解析JSON对象+数组

转载 作者:搜寻专家 更新时间:2023-11-01 03:49:31 25 4
gpt4 key购买 nike

我正在尝试解析以下 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,"temp":
{"day":16.85,"min":10.03,"max":18.15,"night":14.23,"eve":16.32,"morn":16.85},
"pressure":1013.06,"humidity":45,"weather":[
{"id":501,"main":"Rain","description":"light rain","icon":"10d"}],
"speed":15.46,"deg":172,"clouds":88,"rain":1.09},
{"dt":1440504002,"temp":
{"day":16.85,"min":4.73,"max":11.12,"night":14.23,"eve":16.32,"morn":16.85},
"pressure":1013.06,"humidity":59,"weather":[
{"id":502,"main":"Rain","description":"light rain","icon":"10d"}],
"speed":17.12,"deg":172,"clouds":88,"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();
}

其中 String contenidoOW 是 JSON。这段代码给我以下错误:

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

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

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

私有(private)字符串[] tminOWaux;
私有(private)字符串[] tmaxOWaux;
私有(private)长[] humOWaux;
private String[] windOWaux;

感谢您的宝贵时间,非常感谢!

最佳答案

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

关于java - Java解析JSON对象+数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32227028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com