2017-09-07 132 views
0

中希望將空值替換爲空白,其中數據來自JSON格式。將空值替換爲空白

下面是響應有一些數據值爲空的代碼我不想在我的應用程序顯示空,所以我能做些什麼來將null更改爲空白。

String detailsURL = "http://10.0.2.2/xp/details2.php?id="+id+"&gender="+strGender+"&curr_user_id="+current_Id; 
    StringRequest stringRequest = new StringRequest(Request.Method.GET,detailsURL, new Response.Listener<String>() { 
     @Override 
     public void onResponse(String response) { 

       Log.e("details*************",response.trim()); 
       showJSON(response); 
      } 
    }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        Toast.makeText(BlankActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show(); 
       } 
      }); 

    RequestQueue requestQueue = Volley.newRequestQueue(BlankActivity.this); 
    requestQueue.add(stringRequest); 

下面是showJSON功能

private void showJSON(String response){ 
     String fname = ""; 
     String lname = ""; 
     String mobile1 = ""; 
     String emailVC = ""; 
     String height = ""; 
     String weight = ""; 
     String complexion = ""; 
     String body = ""; 
     String diet = ""; 
    try { 
     JSONObject jsonObject = new JSONObject(response); 
     JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY); 
     JSONObject userData = result.getJSONObject(0); 

     fname = userData.getString(Config.KEY_FNAME); 
     lname = userData.getString(Config.KEY_LNAME); 
     mobile1 = userData.getString(Config.KEY_MOBILE1); 
     emailVC = userData.getString(Config.KEY_EMAIL); 
     height = userData.getString(Config.KEY_HEIGHT); 
     weight = userData.getString(Config.KEY_WEIGHT); 
     complexion = userData.getString(Config.KEY_COMPLEXION); 
     body = userData.getString(Config.KEY_BODY); 
     diet = userData.getString(Config.KEY_DIET); 
+1

後showJSON方法 – Raghavendra

+0

我已經發布showJSON方法請檢查 –

+1

它是連擊所有字符串值中的「」(空白),如果如果Array [](空數組),----- ------ so batter to change at service side –

回答

1
if(jsonObject.has("key")) 
{ 
    if (jsonObject.isNull("key")) 
    { 
     String value = ""; 
    } 
} 
+0

什麼是關鍵@Yash –

+0

@VikasGodiyal這裏的關鍵是「Config.KEY_FNAME」 – yash786

+0

所以有很多變量我需要爲大家如果我這樣做,我會花時間 –

1
在showJSON方法

String x = ""; 
if(!response.isNull("key")) { 
    x = response.getString("key"); 
} 
+0

沒有一個變量的響應超過8個變量。 –

+0

恐怕你必須爲每個變量做這件事。 –

+0

我們可以使用替換方法,如response.replace(null,「」); –

1

只要勾選鍵的值是否爲空或不是。例如

if(jsonObject.get("parentId")== null){ 
//do something here 
} 

或者 如果JSON本身是空白

if(jsonObject.length() == 0) 
{ 
//do something here 
} 

或者

if(jsonObject.isNull("parentId")){ 
    jsonObject.put("parentId", SOME_VALUE_HERE); 
} 
+0

是的鍵值爲空,這是顯示在應用程序,所以我需要將空值更改爲空 –

+0

您可以使用我寫的第一種方法或第三種方法。 – Abhinash

+0

其中有8個以上變量的parent_id –

0

解析在一些模型類的響應和在該模型中的getter函數班級,你可以做類似

public Object getObject(){ 
return object==null:new Object:object; 
}