2

我已经完成了有关如何连接到 Json url 并 使用 GSON 库解析内容的教程。该代码适用于本教程中指定的 url,但我尝试对其进行修改以适用于该 Url。我试图只显示第二个 ulr 中的一个字段,即基本字段,但我无法让它工作。这是我的代码,请帮助:

public class JsonParsingActivity extends Activity {

String url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    InputStream source = retrieveStream(url);

    Gson gson = new Gson();// main Gson class

    Reader reader = new InputStreamReader(source);

    SearchResponse response = gson.fromJson(reader, SearchResponse.class); //gson.fromJson(String, Class)

    Toast.makeText(this, response.base, Toast.LENGTH_SHORT).show();
}

private InputStream retrieveStream(String url) {

    DefaultHttpClient client = new DefaultHttpClient(); 

    HttpGet getRequest = new HttpGet(url);

    try {

       HttpResponse getResponse = client.execute(getRequest);
       final int statusCode = getResponse.getStatusLine().getStatusCode();

       if (statusCode != HttpStatus.SC_OK) { 
          Log.w(getClass().getSimpleName(), 
              "Error " + statusCode + " for URL " + url); 
          return null;
       }

       HttpEntity getResponseEntity = getResponse.getEntity();
       return getResponseEntity.getContent();

    } 
    catch (IOException e) {
       getRequest.abort();
       Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
    }

    return null;
 }
}

和 SearchResponse 类:

public class SearchResponse {

@SerializedName("base")
public String base;
}

日志文件:

05-21 14:11:35.559: E/AndroidRuntime(15079): FATAL EXCEPTION: main
05-21 14:11:35.559: E/AndroidRuntime(15079): java.lang.RuntimeException: Unable to           start activity             ComponentInfo{com.example.myproject/com.example.myproject.JsonParsingActivity}: java.lang.IllegalArgumentException: Expected a Class, ParameterizedType, or GenericArrayType, but <com.example.myproject.JsonParsingActivity$1@405494a8> is of type com.example.myproject.JsonParsingActivity$1
05-21 14:11:35.559: E/AndroidRuntime(15079):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at     android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at android.os.Looper.loop(Looper.java:123)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at android.app.ActivityThread.main(ActivityThread.java:3687)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at java.lang.reflect.Method.invokeNative(Native Method)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at java.lang.reflect.Method.invoke(Method.java:507)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at dalvik.system.NativeStart.main(Native Method)
05-21 14:11:35.559: E/AndroidRuntime(15079): Caused by: java.lang.IllegalArgumentException: Expected a Class, ParameterizedType, or GenericArrayType, but <com.example.myproject.JsonParsingActivity$1@405494a8> is of type com.example.myproject.JsonParsingActivity$1
05-21 14:11:35.559: E/AndroidRuntime(15079):    at com.google.gson.internal.$Gson$Types.getRawType($Gson$Types.java:145)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at com.google.gson.reflect.TypeToken.<init>(TypeToken.java:73)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at com.google.gson.reflect.TypeToken.get(TypeToken.java:296)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at com.google.gson.Gson.fromJson(Gson.java:801)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at com.google.gson.Gson.fromJson(Gson.java:768)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at com.example.myproject.JsonParsingActivity.onCreate(JsonParsingActivity.java:42)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-21 14:11:35.559: E/AndroidRuntime(15079):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
05-21 14:11:35.559: E/AndroidRuntime(15079):    ... 11 more
05-21 14:11:44.729: E/AndroidRuntime(15160): FATAL EXCEPTION: main
05-21 14:11:44.729: E/AndroidRuntime(15160): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myproject/com.example.myproject.JsonParsingActivity}: java.lang.IllegalArgumentException: Expected a Class, ParameterizedType, or GenericArrayType, but <com.example.myproject.JsonParsingActivity$1@40547490> is of type com.example.myproject.JsonParsingActivity$1
05-21 14:11:44.729: E/AndroidRuntime(15160):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at android.os.Looper.loop(Looper.java:123)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at android.app.ActivityThread.main(ActivityThread.java:3687)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at java.lang.reflect.Method.invokeNative(Native Method)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at java.lang.reflect.Method.invoke(Method.java:507)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at dalvik.system.NativeStart.main(Native Method)
05-21 14:11:44.729: E/AndroidRuntime(15160): Caused by: java.lang.IllegalArgumentException: Expected a Class, ParameterizedType, or GenericArrayType, but <com.example.myproject.JsonParsingActivity$1@40547490> is of type com.example.myproject.JsonParsingActivity$1
05-21 14:11:44.729: E/AndroidRuntime(15160):    at com.google.gson.internal.$Gson$Types.getRawType($Gson$Types.java:145)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at com.google.gson.reflect.TypeToken.<init>(TypeToken.java:73)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at com.google.gson.reflect.TypeToken.get(TypeToken.java:296)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at com.google.gson.Gson.fromJson(Gson.java:801)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at com.google.gson.Gson.fromJson(Gson.java:768)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at com.example.myproject.JsonParsingActivity.onCreate(JsonParsingActivity.java:42)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-21 14:11:44.729: E/AndroidRuntime(15160):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
05-21 14:11:44.729: E/AndroidRuntime(15160):    ... 11 more
4

1 回答 1

1

我从来没有尝试过使用 Gson 从 Reader 反序列化,但我一直对 JsonElement 很满意。

    HttpURLConnection connection = null;
    JsonElement jsonResponse = null;

    try {
        // create connection
        String url = "http://someplace";
        URL endpoint = new URL(url);
        connection = (HttpURLConnection) endpoint.openConnection();

        // fetch data from server
        JsonReader reader = new JsonReader(new InputStreamReader(connection.getInputStream()));
        JsonParser parser = new JsonParser();
        jsonResponse = parser.parse(reader);

        // parse the response
        Gson gson = new Gson();
        YourResponseClass response;
        try {
            response = gson.fromJson(jsonResponse, YourResponseClass.class);
        } catch (JsonSyntaxException e) { }

        // do something with your object

    } catch (Exception e) {

    } finally {
        // close connection if it's open
        if (connection != null) {
            connection.disconnect();
        }
    }

    ...

您的反序列化类乍一看似乎没问题,只要记住使用 Gson 反序列化时,目标类中的所有类型都必须与 Json 匹配,例如数组、原始类型等。

于 2013-05-21T12:51:44.527 回答