如何在给定JSON响应的retrofit 2.0中编写响应类

时间:2017-06-14 11:00:28

标签: java android api retrofit2

我有一个JSON响应,需要创建一个捕获响应字段的类,以便我可以在我的应用程序中使用它

这是JSON响应:

 {
  "coord": {
    "lon": 24.44,
    "lat": 60.12
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 290.15,
    "pressure": 1006,
    "humidity": 42,
    "temp_min": 290.15,
    "temp_max": 290.15
  },
  "visibility": 10000,
  "wind": {
    "speed": 7.2,
    "deg": 330
  },
  "clouds": {
    "all": 0
  },
  "dt": 1497432000,
  "sys": {
    "type": 1,
    "id": 5019,
    "message": 0.0028,
    "country": "FI",
    "sunrise": 1497401838,
    "sunset": 1497469706
  },
  "id": 649630,
  "name": "Kirkkonummi",
  "cod": 200
}

这是我编写的使用retrofit 2.0的响应类:

package pojo;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;


public class ResultObject<T> {

    @Expose
    @SerializedName("name")
    public String name;


    @Expose
    @SerializedName("id")
    public int id;

    @Expose
    @SerializedName("cod")
    public int cod;


    @Expose
    @SerializedName("dt")
    public long dt;

    @Expose
    @SerializedName("visibility")
    public int visibility;

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

    @Expose
    @SerializedName("main")
    public T main;

    public T getMain() {
        return main;
    }

    @Expose
    @SerializedName("weather")
    public Weather weather;

    public class Weather{

        @Expose
        @SerializedName("description")
        public String description;

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }
    }

    public Weather getWeather() {
        return weather;
    }

}

这是Main类(ResultObject<T>的模板类):

package pojo;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;


public class Main {

    @Expose
    @SerializedName("temp")
    public int temp;

    @Expose
    @SerializedName("pressure")
    public int pressure;

    @Expose
    @SerializedName("humidity")
    public int humidity;

    @Expose
    @SerializedName("temp_min")
    public int temp_min;

    @Expose
    @SerializedName("temp_max")
    public int temp_max;

    public int getTemp() {
        return temp;
    }


    public int getPressure() {
        return pressure;
    }


    public int getHumidity() {
        return humidity;
    }


    public int getTemp_min() {
        return temp_min;
    }


    public int getTemp_max() {
        return temp_max;
    }


}

这是API调用:

 mApi = new RetrofitHelper<AuthApi>().getApi(AuthApi.class);

        currentCall = mApi.currentData(lat,lon,units,key);

        currentCall.enqueue(new Callback<ResultObject<Main>>() {
            @Override
            public void onResponse(Call<ResultObject<Main>> call,
                                   Response<ResultObject<Main>> response) {

                Log.d("enter","enter");
                //Log.d("temp",new Integer(response.body().getMain().getTemp()).toString());
                mData=response.body();
                temp_current.setText(mData.getMain().getTemp());
                status_current.setText(mData.getWeather().getDescription());


                pd.hide();
            }

            @Override
            public void onFailure(Call<ResultObject<Main>> call, Throwable t) {
                Log.d("enterf","Log.getStackTraceString(new Exception())");
                pd.hide();

            }
        });

我记录了始终出现在logcat中的string(enterf),这意味着始终会调用OnFailure方法(我不知道为什么)。

这是logcat:

06-14 16:55:47.052 17452-17650/com.example.kethan.weatherapp D/OkHttp: --> GET http://api.openweathermap.org/data/2.5/weather?lat=19.1334302&lon=72.9132679&units=metric&APPID=dcae12cb0488a2a684320828b6e1acc3 HTTP/1.1
06-14 16:55:47.052 17452-17650/com.example.kethan.weatherapp D/OkHttp: --> END GET
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: <-- 200 OK http://api.openweathermap.org/data/2.5/weather?lat=19.1334302&lon=72.9132679&units=metric&APPID=dcae12cb0488a2a684320828b6e1acc3 (329ms)
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: Server: openresty
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: Date: Wed, 14 Jun 2017 11:25:48 GMT
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: Content-Type: application/json; charset=utf-8
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: Content-Length: 438
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: X-Cache-Key: /data/2.5/weather?APPID=dcae12cb0488a2a684320828b6e1acc3&lat=19.13&lon=72.91&units=metric
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: Access-Control-Allow-Origin: *
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: Access-Control-Allow-Credentials: true
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: Access-Control-Allow-Methods: GET, POST
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: X-Cache: MISS from nm11.iitb.ac.in
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: X-Cache-Lookup: MISS from nm11.iitb.ac.in:80
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: Via: 1.1 nm11.iitb.ac.in (squid/3.3.9)
06-14 16:55:47.382 17452-17650/com.example.kethan.weatherapp D/OkHttp: Connection: close
06-14 16:55:47.383 17452-17650/com.example.kethan.weatherapp D/OkHttp: OkHttp-Sent-Millis: 1497439547129
06-14 16:55:47.383 17452-17650/com.example.kethan.weatherapp D/OkHttp: OkHttp-Received-Millis: 1497439547379
06-14 16:55:47.384 17452-17650/com.example.kethan.weatherapp D/OkHttp: {"coord":{"lon":72.91,"lat":19.13},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main":{"temp":34,"pressure":1005,"humidity":71,"temp_min":34,"temp_max":34},"visibility":6000,"wind":{"speed":5.7,"deg":260},"clouds":{"all":40},"dt":1497436200,"sys":{"type":1,"id":7770,"message":0.0024,"country":"IN","sunrise":1497400227,"sunset":1497448024},"id":6324621,"name":"Powai","cod":200}
06-14 16:55:47.385 17452-17650/com.example.kethan.weatherapp D/OkHttp: <-- END HTTP (438-byte body)
06-14 16:55:47.400 17452-17452/com.example.kethan.weatherapp D/enterf: java.lang.Exception
   at fragments.Home$1.onFailure(Home.java:99)
   at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$2.run(ExecutorCallAdapterFactory.java:75)
   at android.os.Handler.handleCallback(Handler.java:739)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:148)
   at android.app.ActivityThread.main(ActivityThread.java:5441)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

这就是我使用retrofit 2.0的方式:

package helper;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class RetrofitHelper<T> {

    public T getApi(Class<T> tClass){
        return getApi(tClass, QuickPreferences.BASE_URL);
    }

    public T getApi(Class<T> tClass, String URL){
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        httpClient.addInterceptor(logging);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(URL)
                .client(httpClient.build())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit.create(tClass);
    }
}

1 个答案:

答案 0 :(得分:0)

使用以下网站,您可以创建响应类: Convert json to java Object