Android检查JSON响应是否为空

时间:2016-11-16 00:50:55

标签: android json

在Android App中,我需要检查JSON响应是否为空。 这是我的代码:

private void showJSON(String response) {
    String nombre = "";
    String direccion = "";
    String codigo = "";
    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
        JSONObject collegeData = result.getJSONObject(0);
        nombre = collegeData.getString(Config.KEY_NAME);
        direccion = collegeData.getString(Config.KEY_ADDRESS);
        codigo = collegeData.getString(Config.KEY_VC);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (nombre.isEmpty()) {
        nombre = "AGENCIA NO ENCONTRADA";
        textViewResult.setText("Agencia:\t" + nombre);
    }
    else {

        textViewResult.setText("Agencia:\t" + nombre + "\nDireccion:\t" + direccion + "\nCodigo:\t" + codigo);
    }
}

我尝试过:

if (nombre.isEmpty()) {

if (nombre == null) {

if (nombre == "") {

但该应用程序始终显示if条件的else部分。 如果没有来自JSON的数据,输出总是:

Agencia:null Direccion null Codigo:null

如果有数据,则输出是正确的输出。 欢迎任何帮助

1 个答案:

答案 0 :(得分:3)

在android中使用TextUtils.isEmpty()来检查null。 但我认为在你的情况下,nombre不是空的 String nombre =" null&#34 ;;可能在你的情况下。

相关问题