2016-09-11 77 views
1

我試圖顯示從天氣圖中獲得的天氣數據。數據似乎坐在json變量中,但我無法正確解析。解析天氣應用的JSON數據

<current> 
<city id="4459467" name="Cary"> 
<coord lon="-78.78" lat="35.79"/> 
<country>US</country> 
<sun rise="2016-09-11T10:55:38" set="2016-09-11T23:26:18"/> 
</city> 
<temperature value="304.23" min="302.15" max="305.37" unit="kelvin"/>  
<humidity value="45" unit="%"/> 
<pressure value="1018" unit="hPa"/> 
<wind> 
<speed value="2.6" name="Light breeze"/> 
<gusts/><direction value="0" code="N" name="North"/> 
</wind> 
<clouds value="75" name="broken clouds"/> 
<visibility/> 
<precipitation mode="no"/> 
<weather number="803" value="broken clouds" icon="04d"/> 
<lastupdate value="2016-09-11T18:08:01"/></current> 

這是使用正確api密鑰打開天氣的數據。我試圖解析城市,溫度,壓力和溼度。

這裏天氣片段

public class Weather_fragment extends Fragment { 

    TextView cityField; 
    TextView detailsField; 
    TextView currentTemperatureField; 

    Handler handler; 

    public Weather_fragment(){ 
     handler = new Handler(); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.weather_fragment, container, false); 

     cityField = (TextView)rootView.findViewById(R.id.city_field); 
     detailsField = (TextView)rootView.findViewById(R.id.details_field); 
     currentTemperatureField = (TextView)rootView.findViewById(R.id.current_temperature_field); 

     return rootView; 
    } 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     updateWeatherData(new CityPreference(getActivity()).getCity()); 
    } 

    private void updateWeatherData(final String city){ 
     new Thread(){ 
      public void run(){ 
       final JSONObject json = Fetch.getJSON(getActivity(), city); 
       if(json == null){ 
        handler.post(new Runnable(){ 
         public void run(){ 
          Toast.makeText(getActivity(), 
           getActivity().getString(R.string.place_not_found), 
           Toast.LENGTH_LONG).show(); 
         } 
        }); 
       } else { 
        handler.post(new Runnable(){ 
         public void run(){ 
          renderWeather(json); 
         } 
        }); 
       } 
      } 
     }.start(); 
    } 

    private void renderWeather(JSONObject json){ 
     try { 

      cityField.setText(json.getString("name").toUpperCase(Locale.US)); 

      JSONObject main = json.getJSONObject("main"); 
      detailsField.setText("Humidity: " + main.getString("humidity") + "%" + 
       "\n" + "Pressure: " + main.getString("pressure") + " hPa"); 

      currentTemperatureField.setText(String.format("%.2f", main.getDouble("temp"))+ " ℃"); 

     }catch(Exception e){ 
      Log.e("SimpleWeather", "error"); 
     } 
    } 


    public void changeCity(String city){ 
     updateWeatherData(city); 
    } 
} 

這是獲取Java類

public class Fetch { 

    private static final String OPEN_WEATHER_MAP_API = 
     "http://api.openweathermap.org/data/2.5/weather?q="; 

    public static JSONObject getJSON(Context context, String city){ 
     try { 

      String City = "Sydney, AU"; 
      URL url = new URL(String.format(OPEN_WEATHER_MAP_API, City)); 
      HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 

      connection.addRequestProperty("x-api-key", context.getString(R.string.open_weather_maps_app_id)); 

      BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

      StringBuffer Weatherdata = new StringBuffer(); 
      String storage = ""; 
      while((storage=reader.readLine())!=null) { 
       Weatherdata.append(storage + "\n"); 
      } 

      JSONObject data = new JSONObject(Weatherdata.toString()); 
      return data; 
     } catch(Exception e) { 
      return null; 
     } 
    } 
} 
+0

我建議你看一看[ANDROID,解析JSON從Web服務器和顯示數據在ListView](http://stackoverflow.com/a/36243380/2311047) –

+0

數據不是JSON它是在xml –

+0

但您的代碼調用JSON對象 –

回答

0

您需要從JSON響應剝去HTML,然後只有你就能檢索JSONArray然後您可以解析以獲取數據。如下圖所示:

public String stripHtmlResponse (String html) { 
    return Html.fromHtml(html).toString(); 
} 

來源:How to strip HTML tags

然後從JSONArray retrive數據如下

HttpEntity entity = response.getEntity(); 
String data = EntityUtils.toString(entity); 
String noHTML = stripHtml(data); 

JSONArray jsonArray = new JSONArray(noHTML); 

for(int i = 0; i < jsonArray.length(); i++) { 

    // Do parsing of your JSONArray for required data 
} 
+0

所以在完成獲取活動後,我發送給renderweather的JSON對象json需要被分條爲html.There,因爲我會將此代碼與renderweather分開,這是正確的嗎? –

+0

你可以把stripHtmlResponse函數放在類的任何地方。並且在您收到響應對象的地方使用回溯JSONArray代碼。 –

+0

我在代碼的這部分有點遺失。 HttpEntity entity = response.getEntity(); String data = EntityUtils.toString(entity); String noHTML = stripHtml(data); 這顯示爲未定義的變量 我發送JSONObject JSON到striphtmlresponse它仍然是例外在當前時刻。 –