2015-10-31 134 views
0

我的应用程序连接到Web并检索JSON文件。我有一些问题需要从这个文件中检索我需要的数据。这里是链接到JSON文件:http://api.wunderground.com/api/f9d9bc3cc3834375/forecast/q/CA/San_Francisco.json在Android中使用JSON检索数据

这里是什么样子的一个片段: enter image description here

我想获得在内部的第一JSON对象的“期间”变量的值“forecastday”数组,应该是0.下面是我如何看待这个。 “forecastday”是数组,其中有一些JSon对象,每个对象都包含“period”,“icon”,“pop”等变量。在我的代码中,我尝试获取JSON数组“forecastday”,然后获取数组的第一个Json对象,然后在该对象中检索“period”的值并将其设置为TextView:

 protected void onPostExecute(String response) { 
     if(response == null) { 
      response = "THERE WAS AN ERROR"; 
     } 
     progressBar.setVisibility(View.GONE); 


     try { 

      JSONObject jsonObj = new JSONObject(response); 

      JSONArray contacts = jsonObj.getJSONArray("forecastday"); 

      JSONObject c = contacts.getJSONObject(0); 

      String period = c.getString("period"); 

      responseView.setText(period); 

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

当我运行代码时,没有任何内容正在被检索。我新来JSon工作,并想知道如果我看着这个错误。请帮忙。

回答

2

你是接近,但它是不正确,尝试这样的:

JSONObject jsonObj = new JSONObject(response); 
JSONObject forecast = jsonObj.getJSONObject("forecast"); 
JSONObject txtForecast = forecast.getJSONObject("txt_forecast"); 
JSONArray forecastDay = txtForecast.getJSONArray("forecastday"); 

//parse the first period value 
String period = forecastDay.getJSONObject(0).getString("period"); 

responseView.setText(period); 
3

你“forecastday” JSONArray是“txt_forecast”的JSONObject这是你的回应的“预测”的JSONObject内里,让你拥有从这个JSONObject的,而不是从根本JSON响应中提取您的JSONArray:

try { 
    JSONObject jsonObj = new JSONObject(response); 
--> JSONObject forecatsObj = jsonObj.getJSONObject("forecast"); 
--> JSONObject txtForecatsObj = forecatsObj.getJSONObject("txt_forecast"); 
    JSONArray contacts = txtForecatsObj.getJSONArray("forecastday"); 
    ... 
0

试试这个代码:

try { 
    JSONObject jsonObj = new JSONObject(response); 
    JSONObject forecastObj = jsonObj.getJSONObject("forecast"); 
    JSONObject txt_forecastObj = forecastObj.getJSONObject("txt_forecast"); 
    JSONArray foracastdayArray = txt_forecastObj.getJSONArray("foracastday"); 

    JSONObject oOjb0 = foracastdayArray.getJSONObject(0); 
    String period = oOjb0.getString("perioed"); 

}catch (Exception e){ 

} 
0

这段代码适合我:

JSONObject jsonResponse = new JSONObject(responce); 
JSONArray jsonMainNode = jsonResponse.optJSONArray("forecastday"); 
for (int i = 0; i < jsonMainNode.length(); i++) { 
    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 
    String period = jsonChildNode.optString("period"); 
    responceView.setText(period); 
}