Retrofit JSON 解析 - 如何检测数据字段是否存在?
Retrofit JSON parsing - how to detect if data field exists?
REST API 我正在使用 returns JSON 处理数据,以便我可以解析它们。问题是,如果某个值为 0,API 根本不会 return 这样的字段。我需要找到如何在代码中检测到这一点的方法。
JSON 无数据字段:
current
dt 1611128505
sunrise 1611125437
sunset 1611156927
temp 2.88
etc
JSON 数据字段:
current
dt 1611128505
sunrise 1611125437
sunset 1611156927
temp 2.88
precip 1.5 <---here
etc
如何检测数据是否存在?
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
我的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'
POJOclass
@SerializedName("precipitation")
@Expose
public Double precipitation;
理想情况下它不会崩溃,如果您使用 gson
进行序列化,它将忽略 null
值或缺失的字段,因此 field/parameter precipitation
应该有默认值。
您可以使用简单的 try catch 来处理异常并避免崩溃,
但更好的方法是使用一个简单的 if 命令 if 来检查 json 是否为 null 或不像 so
if (weatherPOJO.current.precipitation != null) {
//do your thing
}
REST API 我正在使用 returns JSON 处理数据,以便我可以解析它们。问题是,如果某个值为 0,API 根本不会 return 这样的字段。我需要找到如何在代码中检测到这一点的方法。
JSON 无数据字段:
current
dt 1611128505
sunrise 1611125437
sunset 1611156927
temp 2.88
etc
JSON 数据字段:
current
dt 1611128505
sunrise 1611125437
sunset 1611156927
temp 2.88
precip 1.5 <---here
etc
如何检测数据是否存在?
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
我的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'
POJOclass
@SerializedName("precipitation")
@Expose
public Double precipitation;
理想情况下它不会崩溃,如果您使用 gson
进行序列化,它将忽略 null
值或缺失的字段,因此 field/parameter precipitation
应该有默认值。
您可以使用简单的 try catch 来处理异常并避免崩溃, 但更好的方法是使用一个简单的 if 命令 if 来检查 json 是否为 null 或不像 so
if (weatherPOJO.current.precipitation != null) {
//do your thing
}