我有一個問題,我正在解析JSON對象,並且每個對象中都有22個元素,我想對它們全部進行檢查。我試圖尋找一個解決方案,但無處不在,只是解決方案逐個檢查每個解決方案。有沒有什麼辦法來檢查我的JSON對象中的任何元素是否爲Null,因爲這是一個非常冗長的過程,可以爲22個元素中的每一個單獨執行該操作。以下是我的JSON響應的代碼。Android Volley JSON解析問題NULL檢查
public void onResponse(JSONArray response) {
Log.i("response data", response.toString());
final ArrayList<DataPOJO> list = new ArrayList<>();
try {
JSONArray jArray = response;
Log.i("jArray data", jArray.toString());
for (int i = 0; i < jArray.length(); i++){
JSONObject singleItem = jArray.getJSONObject(i);
DataPOJO data = new DataPOJO();
data.zipcode = singleItem.getInt("zipcode");
data.latitude = singleItem.getDouble("latitude");
data.longitude = singleItem.getDouble("longitude");
data.year = singleItem.getInt("year");
data.make = singleItem.getString("make");
data.model = singleItem.getString("model");
data.transmission = singleItem.getString("transmission");
data.odometer = singleItem.getDouble("odometer");
data.style = singleItem.getString("style");
data.carDescription = singleItem.getString("carDes");
data.advanceNotice = singleItem.getString("advNotice");
data.trim = singleItem.getString("trim");
//data.image = singleItem.getString("carPic");
//data.licenseNumber = singleItem.getString("licenseNo");
//data.issuingCountry = singleItem.getString("issuingCountry");
//data.issuingState = singleItem.getString("issuingState");
//data.licensePlateNumber = singleItem.getString("licensePlateNum");
//data.licenseState = singleItem.getString("licenseState");
//data.lName = singleItem.getString("lNameOnLic");
//data.fName = singleItem.getString("fNameOnLic");
data.minimumDuration = singleItem.getString("shortPT");
data.longestDistance = singleItem.getString("longPT");
list.add(data);
}
} catch (JSONException e) {
Log.e("JSONException: ", e.getMessage());
e.printStackTrace();
}
Log.i("Array list data:",list.toString());
ListView lst = (ListView) findViewById(R.id.car_list);
ListViewAdapter adapter = new ListViewAdapter(list,getApplicationContext());
lst.setAdapter(adapter);
lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent carChoiceIntent = new Intent(getApplicationContext(), CarChoice.class);
carChoiceIntent.putExtra("DataPOJO object", new Gson().toJson(list.get(position)));
startActivity(carChoiceIntent);
}
});
正如你所看到的,我有一個很長的名單來分析其效率非常低爲Null逐個檢查所有這些,它增加了代碼的長度爲好。 如果有人能幫助我,這將是一件好事。我正在使用android Volley庫與服務器進行通信。
謝謝@CzarMatt。它的工作 –