JSONObject remove empty value pairs

前端 未结 6 1074
暖寄归人
暖寄归人 2021-01-05 09:06

Here is my Json File:

{  
   \"models\":{},
   \"path\":[  
      {  
         \"path\":\"/web-profiles\",
         \"operations\":[  
            {  
               


        
6条回答
  •  攒了一身酷
    2021-01-05 09:36

    Don't know about any build-in functions but you could try this

    public boolean cleanJSON(Object arg) throws JSONException{
        boolean valueExist = false;
        if(arg instanceof String){
            String str= (String)arg;
            if(!str.equals("")) valueExist = true;
        }else if(arg instanceof JSONObject){
            JSONObject obj = (JSONObject)arg;
            Iterator iter = obj.keys();
            ArrayList fields = new ArrayList<>();
            while(iter.hasNext())   fields.add(iter.next());
            for(String field:fields){
                Object value = obj.get(field);
                if(cleanJSON(value))    valueExist = true;
                else                    obj.remove(field);
            }
        }else if(arg instanceof JSONArray){
            JSONArray arr = (JSONArray)arg;
            for(int i=0;i

    That would clean your json object from empty field(it work recursively). So if the JSON looks like this:

    "operations":[  
    {  
         "nickname":"",
         "type":"",
         "responseMessages":[]
    }]
    

    field "operations" will also removed.

    note : JSONArray.remove only work for API 19 above

提交回复
热议问题