java递归与非递归实现Json对象的空值/空对象/空数组

文章介绍了三种Java实现方式,用于处理JSON数据,移除其中的空值和空数组,分别使用了Gson、Jackson和自定义方法。
摘要由CSDN通过智能技术生成

test 文件内容:

{
    "user": {
        "code": "U-0000000001",
        "methods": [
            {},
            {}
        ],
        "methods2": {
            "marr": [],
            "marr2": [1,2,3]
        }
    },
    "testNull": null,
    "department": [
        [
            [
                {
                    "name": "layer-map-3"
                }
            ],
            [
                "layer-array-3"
            ],
            [
                33333,
                3.333
            ]
        ]
    ]
}

====java 代码实现方式1:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonStr = getJsonStrFromFile();

        Gson gson = new GsonBuilder().create();
        JsonElement jsonElement = gson.fromJson(jsonStr, JsonElement.class);

        removeEmptyElements(jsonElement);

        String resultJson = gson.toJson(jsonElement);
        System.out.println(jsonStr);
        System.out.println(resultJson);
    }

    private static boolean removeEmptyElements(JsonElement element) {
        if (element.isJsonObject()) {
            JsonObject obj = element.getAsJsonObject();
            for (String key : new HashSet<>(obj.keySet())) {
                JsonElement value = obj.get(key);
                // delete null
                if (value == null || value.isJsonNull()) {
                    obj.remove(key);
                } else if (value.isJsonArray()) {
                    if (!removeEmptyElements(value)) {
                        // delete it when its children.size() == 0
                        obj.remove(key);
                    }
                } else if (value.isJsonObject()) {
                    if (!removeEmptyElements(value)) {
                        obj.remove(key);
                    }
                }
            }
            // return parent loop to judge
            return obj.size() > 0;
        } else if (element.isJsonArray()) {
            JsonArray array = element.getAsJsonArray();
            for (int i = 0; i < array.size(); i++) {
                JsonElement value = array.get(i);
                if (value == null || value.isJsonNull()) {
                    array.remove(i);
                    // Adjust index after removal
                    i--;
                } else if (value.isJsonArray()) {
                    if (!removeEmptyElements(value)) {
                        array.remove(i);
                        // Adjust index after removal
                        i--;
                    }
                } else if (value.isJsonObject()) {
                    if (!removeEmptyElements(value)) {
                        array.remove(i);
                        // Adjust index after removal
                        i--;
                    }
                }
            }
            // return parent loop to judge
            return array.size() > 0;
        }
        return true;
    }

    public static String getJsonStrFromFile() throws Exception {
        String filePath = "c:\\test";

        BufferedReader br = new BufferedReader(new FileReader(filePath));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }

        br.close();

        return sb.toString();
    }
}

=====实现方式2

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.Iterator;

public class JsonUtils {
    
    public static String removeEmptyItems(String jsonStr) throws JsonProcessingException {
        if (StringUtils.isBlank(jsonStr)) {
            return jsonStr;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(jsonStr);
        // remove logic
        removeEmptyElementsLogic(jsonNode);

        return objectMapper.writeValueAsString(jsonNode);
    }

    private static boolean removeEmptyElementsLogic(JsonNode node) {
        if (node.isObject()) {
            ObjectNode objNode = (ObjectNode) node;
            HashSet<String> keysToRemove = new HashSet<>();
            Iterator<String> fieldNames = objNode.fieldNames();
            while (fieldNames.hasNext()) {
                String fieldName = fieldNames.next();
                JsonNode value = objNode.get(fieldName);
                if (value.isNull()) {
                    keysToRemove.add(fieldName);
                } else if (value.isArray() || value.isObject()) {
                    if (!removeEmptyElementsLogic(value)) {
                        keysToRemove.add(fieldName);
                    }
                }
            }

            for (String fieldName : keysToRemove) {
                objNode.remove(fieldName);
            }

            return objNode.size() > 0;
        } else if (node.isArray()) {
            ArrayNode arrayNode = (ArrayNode) node;
            for (int i = 0; i < arrayNode.size(); i++) {
                JsonNode value = arrayNode.get(i);
                if (value.isNull()) {
                    arrayNode.remove(i);
                    i--;
                } else if (value.isArray() || value.isObject()) {
                    if (!removeEmptyElementsLogic(value)) {
                        arrayNode.remove(i);
                        i--;
                    }
                }
            }
            return arrayNode.size() > 0;
        }
        return true;
    }
}

======实现方式3(把上面的 removeEmptyElementsLogic 换成这个方法即可)

    private static Object addNotEmptyObject(Object obj) {
        if (obj instanceof Map) {
            // {}
            Map<String, Object> newMap = new LinkedHashMap<>();
            /*
                {
                    "name": "EEE",
                    "details": [
                        {}
                    ],
                    "details2": [
                        1
                    ],
                    "detailMap": {"dm": "E3/"}
                }
             */
            Map<String, Object> objMap = (Map<String, Object>) obj;
            Iterator<Map.Entry<String, Object>> it = objMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> next = it.next();
                String key = next.getKey();
                Object value = next.getValue();

                if (value != null) {
                    if (value instanceof Map) {
                        // "detailMap": {"dm": "E3/"}
                        Map o = (Map) addNotEmptyObject(value);
                        if (o.size() != 0) {
                            // o = {"dm": "E3/"}
                            newMap.put(key, o);
                        }
                    } else if (value instanceof List) {
                        // "details2": [1] -> [1]
                        List o = (List) addNotEmptyObject(value);
                        if (o.size() != 0) {
                            // "details2": [1]
                            newMap.put(key, o);
                        }
                    } else {
                        // "name": "EEE"
                        newMap.put(key, value);
                    }
                }
            }

            return newMap;

        } else if (obj instanceof List) {
            // "details": [{}] or "details2": [1]
            List<Object> newList = new ArrayList<>();

            List<Object> objList = (List<Object>) obj;
            for(int i=0; i< objList.size(); i++) {
                // {} or 1
                Object value = objList.get(i);

                if (value != null) {
                    if (value instanceof Map) {
                        // {}
                        Map o = (Map) addNotEmptyObject(value);
                        if (o.size() != 0) {
                            newList.add(o);
                        }
                    } else if (value instanceof List) {
                        List o = (List) addNotEmptyObject(value);
                        if (o.size() != 0) {
                            newList.add(o);
                        }
                    } else {
                        // 1
                        newList.add(value);
                    }
                }
            }

            return newList;
        } else {
            return obj;
        }
    }

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值