【问题标题】:How to find out json response is an empty JSON object in android?如何找出 json 响应是 android 中的空 JSON 对象?
【发布时间】:2020-01-25 16:51:18
【问题描述】:

我遇到了从服务器获取空 JSON 对象的问题。

如何确定来自服务器的 JSON 响应是 空 JSON 对象 {}其他? 我为它设置了jObject!=null 条件,但它不起作用。

这是我的代码:

JSONObject jObject = new JSONObject(response);

if (jObject!=null) {
    Toast.makeText(getApplicationContext(), R.string.successfull_unsubscribe, Toast.LENGTH_LONG).show();
    ShareData.saveData(getApplicationContext(), "simType", "null");
    ShareData.saveData(getApplicationContext(), "firstLaunch", "true");

    startActivity(new Intent(MainActivity2.this, WelcomeActivity.class));
    finish();
}

【问题讨论】:

  • 你用的是哪个json库?
  • 我使用 volley 库

标签: java android json rest


【解决方案1】:

你可以试试长度检查或者toString。

例如:jObject.length() == 0

例如:jObject.toString().equals("{}")

【讨论】:

    【解决方案2】:

    您可以使用jObject.keys().hasNext()jObject.length() != 0

    JSONObject jObject = new JSONObject(response);
    if (jObject != null && jObject.length() != 0) {
        Toast.makeText(getApplicationContext(), R.string.successfull_unsubscribe, Toast.LENGTH_LONG).show();
        ShareData.saveData(getApplicationContext(), "simType", "null");
        ShareData.saveData(getApplicationContext(), "firstLaunch", "true");
    
        startActivity(new Intent(MainActivity2.this, WelcomeActivity.class));
        finish();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2021-02-18
      • 1970-01-01
      • 2019-11-10
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多