2017-01-07 20 views
1

在http請求後,有時我的應用程序可能會返回一個空對象,如: ({}) 但是當我測試它是否爲空時,我不會從else得到結果。我如何測試json對象從php web servicec是空的?

JSONObject user = new JSONObject(object); 
          Log.i("",String.valueOf(user.length())); 
          if(user.length()!=0) { 
           String name = user.getString("login"); 
           String passs=user.getString("password"); 
           Toast.makeText(a_log.this, "Bienvenu : "+name, Toast.LENGTH_SHORT).show(); 
           Intent intent = new Intent(a_log.this, MainActivity.class); 
           intent.putExtra("LOGINEE",user.getInt("id")); 
           startActivity(intent);        } 

          else 
          { 
           Toast.makeText(a_log.this, "Vous n'avez pas de compte Veuillez vous inscrire ", Toast.LENGTH_SHORT).show(); 
           Thread.sleep(2500); 
           tv_l.setVisibility(View.VISIBLE); 

          } 
+0

使用'user.length()'時發生了什麼? –

+0

什麼都沒有出現:System.out:pool-2-thread-1調用detatch() –

回答

0

如何從PHP WebService的測試的JSONObject是空的?

隨着JSONObject.length()也使用JSONObject.has(key name)JSONObject.isNull(key name)檢查是JSONObject含有不null鍵:

if(user.length()!=0) { 
    if(user.has("login") && user.isNull("login")){ 

    } 
    .... 
} 
+0

但是user.isNull用於checkinf,如果登錄密鑰爲空而不是相反? –

+0

@HamzaAmrani:是'isNull'是檢查與'key'相關的值。在你的情況都是必需的,所以首先檢查鍵是否存在於JSON對象中,然後在解析 –

+0

之後檢查鍵是否具有有效值再次嘗試工作... –

1

測試你的,如果條件爲 ...

如果(user.has(登陸) )

+0

這篇文章不是實際嘗試回答問題。請注意[StackOverflow不像討論區](http://stackoverflow.com/tour),它是一個問答網站,每個帖子都是問題或問題的答案。帖子也可以有[評論](http://stackoverflow.com/help/privileges/comment) - 這樣的小句子 - 可以用來批評或請求作者澄清。這應該是一個評論或[新問題](http://stackoverflow.com/questions/ask) –