gpt4 book ai didi

java - 尝试将api中的数据获取到JSON时在JSONArray上使用NullPointer

转载 作者:行者123 更新时间:2023-12-01 16:59:11 25 4
gpt4 key购买 nike

我试图将数据从API读取到Json中,以从项目中使用它们。但是我的代码出了点问题,因为它不断向我抛出NullPointer:JSONArray jsonarr_2 = (JSONArray) jsonobj_1.get("table");


代码的其余部分:我试图通过“数据”和“表”,然后从中读取需要的数据。我究竟做错了什么?

Scanner sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+=sc.nextLine();
}
System.out.println("\nJSON Response in String format");
System.out.println(inline);
//Close the stream when reading the data has been finished
sc.close();
}

JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject)parse.parse(inline);
JSONObject jsonarr_1 = (JSONObject ) jobj.get("data");

//Get data for Results array
for(int i=0;i<jsonarr_1.size();i++){

JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
JSONArray jsonarr_2 = (JSONArray) jsonobj_1.get("table");
for(int j=0;j<jsonarr_2.size();j++)
{

JSONObject jsonobj_3 = (JSONObject)jsonarr_2.get(i);
String str_data2 = (String) jsonobj_3.get("Province_State");
Long str_data3 = (Long) jsonobj_3.get("Active");
Long str_data4 = (Long) jsonobj_3.get("Confirmed");
Long str_data5 = (Long) jsonobj_3.get("Deaths");


System.out.println("\n");


API如下所示: API

最佳答案

在下面的行中获取NullPointerException的唯一可能原因

JSONArray jsonarr_2 = (JSONArray) jsonobj_1.get("table");


可以是jobj为null或没有'data'字段/对象。

即使jsonobj_1.get(“ table”)没有给出JSONArray类型的数据,它也应该给出Class强制转换异常,或者jsonarr_2应该为null。

尝试这样做以避免NullPointerException:

if(jsonobj_1!=null && jsonobj_1.has("table")){
JSONArray jsonarr_2 = (JSONArray) jsonobj_1.get("table");
}

关于java - 尝试将api中的数据获取到JSON时在JSONArray上使用NullPointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61539341/

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