【发布时间】:2017-01-05 11:37:32
【问题描述】:
我正在尝试从 url 解析 json 代码,但我看不到我的错误,因为我没有得到任何结果。这是我的代码:
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall("http://api.apixu.com/v1/forecast.json?key=93a1531ba64540f7a41180856163011&q=bilbao&days=1", ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject fore = jsonObj.getJSONObject("forecast");
// Getting JSON Array node
eventos = fore.getJSONArray("forecastday");
porhoraca = fore.getJSONArray("hour");
for (int i = 0; i < porhoraca.length(); i++) {
JSONObject c = porhoraca.getJSONObject(i);
String hora = c.getString(TAG_TIME);
String tempec = c.getString(TAG_TEMP_C);
String sensacion = c.getString(TAG_FEELSLIKE_C);
JSONObject condi = c.getJSONObject(TAG_CONDITION);
String texto = condi.getString(TAG_TEXT);
String icono = condi.getString(TAG_ICON);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("nombre", hora);
contact.put("hora", tempec);
contact.put("nombre_lugar", sensacion);
contact.put("coordenadas", texto);
contact.put("info", icono);
// adding contact to contact list
eventosList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
我只想从包含 json 的 url 中获取这些对象。有些我做错了。也许我没有正确阅读 json 对象和 Json 数组。有人可以说我的错误在哪里?谢谢
Json 代码在这里:
http://api.apixu.com/v1/forecast.json?key=93a1531ba64540f7a41180856163011&q=bilbao&days=1
【问题讨论】:
-
考虑使用
gsonlibrary....它会让你的生活更轻松! -
@Androi: `Log.d("Response: ", "> " + jsonStr);` 行中有什么数据?
-
您想从中获得什么 - 位置、预测或当前?
-
调试它。添加日志。尝试一个接一个地记录跟踪 json 对象。它有助于理解你的错误
-
您可以使用在线 Json 解析器,例如 this,这将有助于您理解 Json 对象。只需复制粘贴 GET 结果并点击查看器选项卡。另外,如前所述,我建议您使用其中一个优秀的库。
标签: android json android-asynctask