简体   繁体   中英

How to write response class in retrofit 2.0 given JSON response

I have got a JSON response, need to create a class that captures the response fields so that I can use it in my app

This is the JSON response:

 {
  "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
}

This is the response class I have written to use 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;
    }

}

This the Main class (template class for the 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;
    }


}

This is the API call:

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

            }
        });

I logged the string(enterf) that always appears in the logcat that means OnFailure method is called always (I don't know why).

This is the 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)

This is how I use 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);
    }
}

在下面的网站上,您可以创建响应类: 将json转换为java对象

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM