使用GSON库从URL(RESTful webservice)解析JSON字符串。 Android的

时间:2012-01-10 15:31:06

标签: android json url rest gson

阅读之前:我在这个程序中使用了可下载的GSON库。 http://webscripts.softpedia.com/script/Development-Scripts-js/Other-Libraries/Gson-71373.html

我一直在尝试解析JSON很长一段时间,但每次我尝试从URL中获取字符串时程序都“无法正常工作”。它不会失败或关闭或出错。它只是不解析。我的程序是从http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo解析并有一个更新按钮再次运行解析过程,以便它刷新信息。如果我使用硬编码的JSON字符串,该程序可以正常工作。我甚至放入了应该从URL中检索的字符串;但我似乎无法直接得到它。我正在使用GSON库。

在代码中,我提供了解释我思考过程的评论。请注意,我有2种不同的方法试图使用URL(我认为可能原来的一个是错的所以我试图使用另一个),这是我抓住稻草。请帮帮我。谢谢。

我的代码:

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();
        }

    }
}

3 个答案:

答案 0 :(得分:2)

像谢尔盖一样,我发现Android上包含的json库org.json.*GSON更容易使用。

例如,在您的场景中 - 您的JSON解析代码将如下所示。

String jsonData = readUrl("http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo");
JSONObject weatherJSONObject = new JSONObject( jsonData );

try {
    // Not sure the format of your data, but you would want something like this
    String clouds = weatherJSONObject.getString("clouds");
} catch (JSONException e) {
    e.printStackTrace();
}

您还可以从AsyncTaskThread中受益。您永远不希望在UI线程上运行长时间运行的操作,因为UI看起来没有响应和缓慢。

以下是有关如何使用AsyncTask实现目标的示例。详细了解here

private class FetchJSONDataTask extends AsyncTask<String, Void, JSONObject> {

     // This gets executed on a background thread
     protected JSONObject doInBackground(String... params) {
         String urlString = params[0];
         String jsonData = readUrl( urlString );
         JSONObject weatherJSONObject = new JSONObject( jsonData );
         return weatherJSONObject;
     }

     // This gets executed on the UI thread
     protected void onPostExecute(JSONObject json) {
         //Your function that takes a json object and populates views
         setUpViews( json );
     }
 }

要执行您的任务,您应该在您的活动中运行此代码。

FetchJSONDataTask task = new FetchJSONDataTask();
task.execute( new String[] { "http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo" } );

注意:此代码未经测试,但这应该是一般的想法。

答案 1 :(得分:0)

我使用org.json完成了json解析。*

http://www.json.org/java/index.html Android 4中的文档。 http://developer.android.com/reference/org/json/package-summary.html(例如)

您可以从这里下载jar http://repo1.maven.org/maven2/org/json/json/20090211/json-20090211.jar

我还会考虑在不同的线程中运行您的http请求,然后重新绘制您的UI。为此目的也读了关于android.os.Handler的信息。

感谢

答案 2 :(得分:0)

JSON响应通常是gzip,请在getJSONData()方法中尝试:

... ...
uri = new URI(url);
HttpGet method = new HttpGet(uri); // Get URI
HttpResponse response = httpClient.execute(method); // Get response from method.
InputStream in = response.getEntity().getContent();
GZIPInputStream gin = new GZIPInputStream(in);
BufferedReader reader = new BufferedReader(new InputStreamReader(gin));
String line = null;
while ((line = reader.readLine()) != null) {
    jsonResponse.append(line);
}
reader.close();
... ...