Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONObject remove empty value pairs

Here is my Json File:

{  
   "models":{},
   "path":[  
      {  
         "path":"/web-profiles",
         "operations":[  
            {  
               "type":"",
               "responseMessages":[]
            }
         ]
      }
   ],
   "produces":[]
}

If the values of keys are empty (includes [], "", {}). How can I remove those pairs from Json file.

  1. I tried to use JSONObject build-in functions to remove unnecessary pairs. But, it didn't work.
  2. I tried to use string method to process it line by line. It got too many cases, I can't cover all of those cases in my code. (for example, the sub-key 'operations', when you want to remove all empty value, this key(operations) value pair also should be removed.) Any ideas?
like image 561
A Phototactic Coder Avatar asked Jun 25 '15 00:06

A Phototactic Coder


1 Answers

First, you should deserialize json to a Map<String, Object>. Second, loop the map entry to find out what key has null value or what key has value is instance of ArrayList but empty and remove from the Map. Last, serialize the Map to json.

Try this code:

String json = "{'a': 'apple', 'b': 'ball', 'c': 'cat', 'd': null, 'e': []}";
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> data = new Gson().fromJson(json, type);

for (Iterator<Map.Entry<String, Object>> it = data.entrySet().iterator(); it.hasNext();) {
    Map.Entry<String, Object> entry = it.next();
    if (entry.getValue() == null) {
        it.remove();
    } else if (entry.getValue() instanceof ArrayList) {
        if (((ArrayList<?>) entry.getValue()).isEmpty()) {
            it.remove();
        }
    }
}

json = new GsonBuilder().setPrettyPrinting().create().toJson(data);
System.out.println(json);
like image 161
codeaholicguy Avatar answered Oct 12 '22 12:10

codeaholicguy