Android如何检查JSON响应是否为空?

3

在 Android 应用中,我需要检查 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条件的另一部分。当JSON没有数据时,输出始终为:

机构:null 地址:null 代码:null

如果有数据,则输出正确。任何帮助都受欢迎。
1个回答

3
在Android中,使用TextUtils.isEmpty()来检查null。但我认为在你的情况下,nombre并不是null。
在你的情况下,String nombre = "null"; 可能是正确的。

你是正确的,在我的情况下,nombre == "null" 是正确的。谢谢。 - mvasco
很高兴能帮助您!;-) - Lazy Ninja

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接