Josef Vancura
Josef Vancura

Reputation: 1180

Retrofit JSON parsing - how to detect if data field exists?

REST API I am using returns JSON with data so I can parse them. Problem is that if some value is 0, API will not return such field at all. I need to find the way how to detect this in code.

JSON without data field:

current 
 dt 1611128505
 sunrise    1611125437
 sunset 1611156927
 temp   2.88
etc

JSON with data field:

current 
  dt    1611128505
  sunrise   1611125437
  sunset    1611156927
  temp  2.88
  precip 1.5 <---here
 etc
  

How do detect if data exists ?

 Call<RetrofitWeatherPOJO> call = apiInterface.doGetWeather(Lat, Lon, ApiKey, units);
        call.enqueue(new Callback<RetrofitWeatherPOJO>() {
            @Override
            public void onResponse(Call<RetrofitWeatherPOJO> call, Response<RetrofitWeatherPOJO> response) {

    RetrofitWeatherPOJO weatherPOJO = response.body();

    double TempCurrent = weatherPOJO.current.temp;
    double HumCurrent = weatherPOJO.current.humidity;
    double PrercipCurrent = weatherPOJO.current.precipitation; <-- will crash if JSON missing data

my gradle

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'

POJO class

  @SerializedName("precipitation")
  @Expose
  public Double precipitation;

Upvotes: 1

Views: 453

Answers (2)

Learnaholic
Learnaholic

Reputation: 175

you can use a simple try catch to handle the exception and avoid crashes, but a better way would be to use a simple if command if to check if the json is null or not like so

if (weatherPOJO.current.precipitation != null) {
                //do your thing
        
 }

Upvotes: 2

Rajan Kali
Rajan Kali

Reputation: 12953

Ideally it won't crash, if you are using gson for serialisation it will ignore null values or missing fields , hence the field/parameter precipitation should have default value.

Upvotes: 0

Related Questions