Remove empty collections from a JSON with Gson

后端 未结 3 1452
滥情空心
滥情空心 2020-11-30 11:51

I want to remove attributes that have empty collections or null values using gson.

Aiperiodo periodo = periodoService();
//periodo comes fro         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 12:52

    I have code that can process array or object with different structure and will remove "empty collections or null values" recursively. It works with String not with Gson directly. If it's not critical, it can help you.

    Your code will be:

    Aiperiodo periodo = periodoService();
    //periodo comes from a service method with a lot of values
    Gson gson = new Gson();
    String json = gson.toJson(periodo);
    json = removeNullAndEmptyElementsFromJson(json);
    

    ...

    import com.google.gson.GsonBuilder;
    import com.google.gson.JsonElement;
    import com.google.gson.JsonParser;
    
    import java.util.Iterator;
    import java.util.Map;
    
    public class IoJ {
    
    public static void main(String[] args) {
        String j = "{\"query\":\"\",\"name\":null,\"result\":{\"searchResult\":[{\"id\":null,\"phone\":\"123456\",\"familyAdditionalDetails\":[],\"probability\":0.0,\"lastUpdated\":\"2019-05-18T12:03:34Z\",\"empty\":false,\"gender\":\"F\"}]},\"time\":1558181014060}";
    
        // {"query":"","name":null,"result":{"searchResult":[{"id":null,"phone":"123456","familyAdditionalDetails":[],"probability":0.0,"lastUpdated":"2019-05-18T12:03:34Z","empty":false,"gender":"F"}]},"time":1558181014060}
        System.out.println(j);
        // (additional spaces for easier check)
        // {"query":"",            "result":{"searchResult":[{          "phone":"123456",                             "probability":0.0,"lastUpdated":"2019-05-18T12:03:34Z","empty":false,"gender":"F"}]},"time":1558181014060}
        System.out.println(removeNullAndEmptyElementsFromJson(j));
    }
    
    public static String removeNullAndEmptyElementsFromJson(String jsonString) {
        if (jsonString == null) {
            return jsonString;
        }
        try {
            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(jsonString);
            cleanByTree(element);
            jsonString = new GsonBuilder().disableHtmlEscaping().create().toJson(element);
            return jsonString;
        } catch (Exception e) {
            return jsonString;
        }
    }
    
    private static void cleanByTree(JsonElement e1) {
        if (e1 == null || e1.isJsonNull()) {
    
        } else if (e1.isJsonArray()) {
            for (Iterator it = e1.getAsJsonArray().iterator(); it.hasNext(); ) {
                JsonElement e2 = it.next();
                if (e2 == null || e2.isJsonNull()) {
                    //it.remove();
                } else if (e2.isJsonArray()) {
                    if (e2.getAsJsonArray().size() == 0) {
                        it.remove();
                    } else {
                        cleanByTree(e2);
                    }
                } else if (e2.isJsonObject()) {
                    cleanByTree(e2);
                }
            }
        } else {
            for (Iterator> it = e1.getAsJsonObject().entrySet().iterator(); it.hasNext(); ) {
                Map.Entry eIt = it.next();
                JsonElement e2 = eIt.getValue();
                if (e2 == null || e2.isJsonNull()) {
                    //it.remove();
                } else if (e2.isJsonArray()) {
                    if (e2.getAsJsonArray().size() == 0) {
                        it.remove();
                    } else {
                        cleanByTree(e2);
                    }
                } else if (e2.isJsonObject()) {
                    cleanByTree(e2);
                }
            }
        }
    }
    
    }
    

提交回复
热议问题