Parsen der JSON-string aus der URL (RESTful-webservice) mit GSON Bibliotheken. Android

Bevor Sie weiterlesen: ich habe herunterladbare GSON Bibliotheken in dieses Programm.
http://webscripts.softpedia.com/script/Development-Scripts-js/Other-Libraries/Gson-71373.html

Ich habe versucht zu Parsen von JSON für einige Zeit jetzt, aber jedes mal, wenn ich versuche, den string aus dem URL das Programm nicht "arbeiten". Es nicht scheitern oder zu schließen oder Fehler. Es funktioniert einfach nicht analysieren. Mein Programm soll zu Parsen http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo und verfügt über eine Schaltfläche zum aktualisieren, führen Sie die Analyse erneut, so dass Sie aktualisieren Sie die Informationen. Wenn ich eine fest codierte JSON-string, funktioniert das Programm perfekt. Ich selbst in der Zeichenfolge werden soll, werden aus der URL, aber ich kann nicht scheinen, um in der Lage sein, um es direkt. Ich benutze GSON Bibliotheken.

Im code habe ich Kommentare, um zu erklären, meine Gedanken. Beachten Sie, dass ich 2 verschiedene Methoden, die versuchen, verwenden Sie die URL (ich dachte, dass die vielleicht das original falsch war, so versuchte ich ein anderes verwenden), das war mir greifen nach Strohhalmen. Bitte helfen Sie mir. Danke.

Mein Code:

package com.android.testgson;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;

public class GSONTestActivity extends Activity {
    /** Called when the activity is first created. */

    //String test = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView tv = (TextView)findViewById(R.id.textViewInfo);
        syncButtonClickListener();

        runJSONParser(tv);

    }

    private void syncButtonClickListener() 
    {

        Button syncButton = (Button)findViewById(R.id.buttonSync);
        syncButton.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
                TextView tv = (TextView)findViewById(R.id.textViewInfo);
                runJSONParser(tv);
            }
        });
    }


    public InputStream getJSONData(String url){
        //create DefaultHttpClient
        HttpClient httpClient = new DefaultHttpClient();
        URI uri; //for URL
        InputStream data = null; //for URL's JSON

        try {
            uri = new URI(url);
            HttpGet method = new HttpGet(uri); //Get URI
            HttpResponse response = httpClient.execute(method); //Get response from method.  
            data = response.getEntity().getContent(); //Data = Content from the response URL. 
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }

    public void runJSONParser(TextView tv){
        try{
            Gson gson = new Gson();
            //Reader r = new InputStreamReader(getJSONData("http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo"));
            /**I tried parsing the URL, but it didn't work. No error messages, just didn't parse.*/
            //Reader r = new InputStreamReader(getJSONData("android.resource://"+ getPackageName() + "/" + R.raw.yourparsable));
            /**I tried parsing from local JSON file. Didn't work. Again no errors. The program simply stalls. */

            //String testString = "{\"weatherObservation\":{\"clouds\":\"few clouds\",\"weatherCondition\":\"n/a\",\"observation\":\"LSZH 041320Z 24008KT 210V270 9999 FEW022 SCT030 BKN045 05/01 Q1024 NOSIG\",\"windDirection\":\"240\",\"ICAO\":\"LSZH\",\"elevation\":\"432\",\"countryCode\":\"CH\",\"lng\":\"8.516666666666667\",\"temperature\":\"5\",\"dewPoint\":\"1\",\"windSpeed\":\"08\",\"humidity\":\"75\",\"stationName\":\"Zurich-Kloten\",\"datetime\":\"2012-01-04 13:20:00\",\"lat\":\"47.46666666666667\",\"hectoPascAltimeter\":\"1024\"}}";
            /**If I parse this string. The parser works. It is the same exact string like in the URL.*/
            //String failString = "{\"status\":{\"message\":\"the hourly limit of 2000 credits demo has been exceeded. Please throttle your requests or use the commercial service.\",\"value\":19}}";
            /**Even if the url delivers this string (because the hourly limit would be reached), the string is still parsed correctly.*/
            String json = readUrl("http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo");
            /**At this point I tried a different means of accessing the URL but still I had the exact same problem*/

            Observation obs = gson.fromJson(json, Observation.class);
            //"json" can be replaced with r, testString, failString to see all my previous results.

            if (obs.getWeatherObservation()!=null)
            {
                tv.setText("Clouds - " + obs.getWeatherObservation().getClouds()
                        + "\nTemperature - " + obs.getWeatherObservation().getTemperature()
                        + "\nWind Speed - " + obs.getWeatherObservation().getWindSpeed()
                        + "\nHumidity - " + obs.getWeatherObservation().getHumidity());
            }
            else if (obs.getStatus()!=null)
            {
                tv.setText("Message - " + obs.getStatus().getMessage()
                        + "\nValue - " + obs.getStatus().getValue());
            }

        }catch(Exception ex){
            ex.printStackTrace();
        }

    }

    public static String readUrl(String urlString) throws Exception {
        BufferedReader reader = null;

        try{
            URL url = new URL(urlString);
            reader = new BufferedReader(new InputStreamReader (url.openStream()));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[]chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read); 

            return buffer.toString();
        } finally {
            if (reader != null)
                reader.close();
        }

    }
}
Könntest du deinen post Observation.java?
Haben Sie sichergestellt, dass readURL ist infact die Rückgabe der Zeichenfolge, die Sie erwarten?

InformationsquelleAutor user1028408 | 2012-01-10

Schreibe einen Kommentar