【问题标题】:Android getting JSONObject ExceptionAndroid 获取 JSONObject 异常
【发布时间】:2015-10-03 03:08:42
【问题描述】:

如果我的 JSON 对象 media 中的 twitter 值在下面的代码中为空,我会收到 JSONObject 异常,即使我检查以确保我没有将值分配给任何东西是。我检查的方式是否正确?或者如何避免我的代码抛出异常并允许我检查 twitter 值是否存在?

if(nextActivityObject.getJSONObject("media") != null){

    media = nextActivityObject.getJSONObject("media");
    Log.d("NEXT MEDIA OBJECT NOT EMPTY", media.toString());

    if(media.getString("twitter") != null &&  media.getString("facebook") != null){
         Log.d("BOTH NOT NULL", "both not null");
         twitter = media.getString("twitter");
         facebook = media.getString("facebook");

          intent.putExtra("twitter", twitter);
          intent.putExtra("facebook", facebook);
      }
      else if(media.getString("twitter") != null){

           twitter = media.getString("twitter");
           Log.d("JUST TWITTER NOT NULL", twitter.toString());
           intent.putExtra("twitter", twitter);
      }
      else if(media.getString("facebook") != null){
          facebook = media.getString("facebook");
          Log.d("JUST FACEBOOK NOT NULL", facebook.toString());
          intent.putExtra("facebook", facebook);
      }
  }

【问题讨论】:

    标签: android null org.json jsonexception


    【解决方案1】:

    您可以使用media.optString("twitter");。你需要另一个media.has("twitter") 来区分“没有名为twitter 的键”和“twitter 键有空字符串值”。

    总而言之,对于“twitter”键,你可以写

     else if(media.has("twitter")){
           twitter = media.optString("twitter");
           // here twitter is non-NULL String
           Log.d("JUST TWITTER NOT NULL", twitter.toString());
           intent.putExtra("twitter", twitter);
      }
    

    【讨论】:

    • 我试过media.optString("twitter"),但没有运气。我检查了我的 JSON 对象响应,在它崩溃的情况下,值是 {'facebook' : ....'} 并且没有 twitter,所以在这种情况下,我会使用 .has 来检查那个“无键”情况?
    • @ralphie9224 我在答案中再次进行了总结。使用opt*() 而不是get*() 将异常处理更改为空引用/空字符串/ NaN 值检查。
    【解决方案2】:

    使用 .has 方法判断 key 是否在 json 中。明智的做法是使用 optString,而不是 getString。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多