【问题标题】:getJSONObject and subsequent getString returns nullgetJSONObject 和后续的 getString 返回 null
【发布时间】:2016-06-22 05:20:00
【问题描述】:

这是一个非常直截了当的问题,但这个错误对我来说非常神秘,因为我无法找到解决方案或任何遇到此问题的人。我还在另一项活动中使用了一种非常相似的技术,并且效果很好。我正在制作一个向服务器发出POST 请求的android 应用程序。响应是一个必须解析为数字的JSONObject 和另一个也必须解析的JSONObject,并将其值分配给CurrentGame 对象的数组。第一次调用 getJSONObject 工作正常,但在该 JSONObject 上调用 getString 会返回以下错误:

java.lang.NullPointerException: Attempt to write to field 'java.lang.String com.xxxxx.xxxxx.CurrentGame.oppEmail' on a null object reference

这是我的java代码:

private void handleResponse(JSONObject response){
    int numGroups = 0;
    try{
        numGroups = response.getInt("Number");
    }catch(JSONException e){
        e.printStackTrace();
    }
    Log.i("Number of Groups", String.valueOf(numGroups));

    CurrentGame[] currentGames = new CurrentGame[numGroups];
    JSONObject current;
    int yourTurn = 0;
    for(int i = 0; i < numGroups; i++){
        try{
            current = response.getJSONObject(String.valueOf(i));
            Log.i("Current JSONObject: ", String.valueOf(current));
            if(current.has("OppEmail")){
                currentGames[i].oppEmail = current.getString("OppEmail");
            }
            if(current.has("OppName")) {
                currentGames[i].oppName = current.getString("OppName");
            }
            if(current.has("Group")) {
                currentGames[i].group = current.getString("Group");
            }
            if(current.has("YourTurn")) {
                yourTurn = current.getInt("YourTurn");
            }
            if(yourTurn == 0){
                currentGames[i].yourTurn = true;
            }
            else{
                currentGames[i].yourTurn = false;
            }
        }
        catch (JSONException e){
        e.printStackTrace();
        }
    }
}

JSONObject.has() 检查不应该至少防止这个错误吗?

我知道第一个 getInt()getJSONObject 正在工作。这是日志:

06-21 21:58:56.644  20116-20116/com.xxxxx.xxxxx D/Response:﹕ {"Number":2,"0":{"Group":"Test Group 1","OppEmail":"xxxxx@xxxxx.edu","OppName":"MikeyP","YourTurn":0},"1":{"Group":"Test Group 2","OppEmail":"xxxxx@xxxxx.edu","OppName":"MikeyP","YourTurn":1}}
06-21 21:58:56.644  20116-20116/com.xxxxxx.xxxxxt I/Number of Groups﹕ 2
06-21 21:58:56.644  20116-20116/com.xxxxx.xxxxx I/Current JSONObject﹕ {"Group":"Test Group 1","OppEmail":"xxxxxx@xxxxx.edu","OppName":"MikeyP","YourTurn":0}

这是服务器代码:

$games['Number'] = $numgames;
if($numgames > 0){
  $i = 0;
  while($row = mysqli_fetch_array($getgames)){
      $currGame['Group'] = $row['GroupName'];

      // Get the opponent's email and username
      if($row['Player1'] != $email){
          $opponent = $row['Player1'];
          $currGame['OppEmail'] = $opponent;
          $sql = "SELECT Username FROM users WHERE Email = '".$opponent."'";
          $username = mysqli_query($conn, $sql);
          $row2 = mysqli_fetch_assoc($username);
          $currGame['OppName'] = $row2['Username'];
      }
      else if($row['Player2'] != $email){
          $opponent = $row['Player2'];
          $currGame['OppEmail'] = $opponent;
          $sql = "SELECT Username FROM users WHERE Email = '".$opponent."'";
          $username = mysqli_query($conn, $sql);
          $row2 = mysqli_fetch_assoc($username);
          $currGame['OppName'] = $row2['Username'];
      }

      // Determine if it is this player's turn
      if($row['CurrentPlayer'] != $email){
          $currGame['YourTurn'] = 0;
      }
      else{
          $currGame['YourTurn'] = 1;
      }

      $games[$i] = $currGame;
      $i++;
  }
}
//Echo array of groups
header('Content-Type: application/json');
$response = json_encode($games);
echo $response;

提前感谢您对我在这里做错的任何想法。我知道有人问过关于getString() 返回null 的类似问题,但读完所有内容后我仍然很困惑。

【问题讨论】:

    标签: java php android json post


    【解决方案1】:

    问题是由以下原因引起的:

    currentGames[i].oppEmail = current.getString("OppEmail");
    

    行。

    因为currentGames 数组初始化为大小为 2,但未添加任何 CurrentGame 类型的项目。

    而不是使用currentGames[i].oppEmail 创建CurrentGame 类的对象添加所有值,然后将其添加到currentGames 数组中,如:

    CurrentGame objCurrentGame=new CurrentGame();
    if(current.has("OppEmail")){
      objCurrentGame.oppEmail = current.getString("OppEmail");
    }
    ... same for other fields 
    ...
    //Add objCurrentGame to Array
    currentGames[i]=objCurrentGame;
    

    【讨论】:

      【解决方案2】:

      这种方式解析json不健壮且容易出错,推荐使用

      之类的库

      因为这些开源库为此目的提供了稳定的实现,无需自己重新发明轮子。

      示例:

      YourPojoClass obj = new Gson().fromJson("{SomeJsonString}", YourPojoClass.class);
      

      这样就得到了强类型的pojo实例,甚至不需要自己写POJO类,网上有很多服务可以用json字符串生成POJO类:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多