我正在尝试运行以下代码,但它正在抛出异常。
代码
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("current");
} catch (JSONException e) {
e.printStackTrace();
}
主要的例外是由于JSONArray部分。如果删除该部分,则代码运行正常。
以下是API:
{
"location": {
"name": "Paris",
"region": "Ile-de-France",
"country": "France",
"lat": 48.87,
"lon": 2.33,
"tz_id": "Europe/Paris",
"localtime_epoch": 1480463619,
"localtime": "2016-11-29 23:53"
},
"current": {
"last_updated_epoch": 1480463580,
"last_updated": "2016-11-29 23:53",
"temp_c": -1,
"temp_f": 30.2,
"is_day": 0,
"condition": {
"text": "Clear",
"icon": "//cdn.apixu.com/weather/64x64/night/113.png",
"code": 1000
},
"wind_mph": 0,
"wind_kph": 0,
"wind_degree": 0,
"wind_dir": "N",
"pressure_mb": 1033,
"pressure_in": 31,
"precip_mm": 0,
"precip_in": 0,
"humidity": 69,
"cloud": 0,
"feelslike_c": -1,
"feelslike_f": 30.2
}
}
发生异常:
W/System.err: org.json.JSONException: Value {"last_updated_epoch":1480477541,"last_updated":"2016-11-30 03:45","temp_c":13,"temp_f":55.4,"is_day":0,"condition":{"text":"Overcast","icon":"\/\/cdn.apixu.com\/weather\/64x64\/night\/122.png","code":1009},"wind_mph":0,"wind_kph":0,"wind_degree":0,"wind_dir":"N","pressure_mb":1016,"pressure_in":30.5,"precip_mm":0,"precip_in":0,"humidity":77,"cloud":0,"feelslike_c":13,"feelslike_f":55.4} at current of type org.json.JSONObject cannot be converted to JSONArray
答案 0 :(得分:2)
在Json
中,current
似乎是一个对象而不是数组。如此改变
jsonObject.getJSONArray("current");
到
jsonObject.getJSONObject("current");
将修复错误。
答案 1 :(得分:1)
答案 2 :(得分:-1)
你可以简单地使用Gson库将所有这些json转换为对象类。很容易获取和设置而不必一次又一次地迭代json。
创建模型类名称 LocationModel
public class LocationModel
{
private Location location;
private Current current;
//create setter and getter
}
为当前对象
创建模型public class Current
{
private String temp_f;
private Condition condition;
private String temp_c;
private String wind_degree;
private String wind_dir;
private String wind_kph;
private String is_day;
private String pressure_in;
private String humidity;
private String precip_mm;
private String wind_mph;
private String pressure_mb;
private String feelslike_f;
private String cloud;
private String last_updated_epoch;
private String feelslike_c;
private String last_updated;
private String precip_in;
//create setter and getter
}
创建条件模型类
public class Condition
{
private String icon;
private String text;
private String code;
//create setter and getter
}
创建位置模型类
public class Location
{
private String region;
private String localtime;
private String localtime_epoch;
private String lon;
private String tz_id;
private String name;
private String lat;
private String country;
//create setter and getter
}
如何使用?
LocationModel locationM = new Gson().fromJson(**YOURJSONSTRING**,LocationModel.class);
locationM.getLocation().getRegion(); //get Region <br>
locationM.getCurrent().getCondition().getText(); //get condition text from current<br>
locationM.getCurrent().getHumidity(); //get current humidity<br>