ObjectMapper比较两个Java对象、json对象,反序列化时将空字符串转为null

package com.wyy.sourceCode;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

public class Om1 {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();

        /*
            {"s1":"k1", "s2":"", "s3":null, "s4":{"p1":"k1", "p2":"", "p3":["d1","d2"]}}
            {"s1":"k1","s2":"null","s3":null,"s4":{"p1":"k1","p2":"null","p3":["d1","d2"]}}

         */

        String w1 = "{\"s1\":\"k1\", \"s2\":\"\", \"s3\":null, \"s4\":{\"p1\":\"k1\", \"p2\":\"\", \"p3\":[\"d1\",\"d2\"]}}";
//        String w3 = "{\n" +
//                "  \"s1\": \"k1\",\n" +
//                "  \"s2\": \"null\",\n" +
//                "  \"s3\": null,\n" +
//                "  \"s4\": {\n" +
//                "    \"p1\": \"k1\",\n" +
//                "    \"p2\": \"null\",\n" +
//                "    \"p3\": [\n" +
//                "      \"d1\",\n" +
//                "      \"d2\"\n" +
//                "    ]\n" +
//                "  },\n" +
//                "  \"s5\": [\n" +
//                "    {\n" +
//                "      \"l1\": \"pp\",\n" +
//                "      \"l2\": null,\n" +
//                "      \"l3\": \"\",\n" +
//                "      \"l4\": {\"k1\": null, \"k2\": \"\", \"k3\": [1,2,3]}\n" +
//                "    }\n" +
//                "  ]\n" +
//                "}";
        // objectMapper.registerModule();
        JsonNode jsonNode = objectMapper.readTree(w1);
        jsonLeaf(jsonNode);
        System.out.println(jsonNode);

        String w2 = "{\"s1\":\"k1\", \"s2\":\"\", \"s3\":null, \"s4\":{\"p3\":[\"d1\",\"d2\"], \"p1\":\"k1\", \"p2\":\"\"}}";
        JsonNode jsonNode2 = objectMapper.readTree(w2);
        jsonLeaf(jsonNode2);
        System.out.println(jsonNode2);
        System.out.println(jsonNode.equals(jsonNode2));
    }

    public static void jsonLeaf(JsonNode node) {
        if (node.isObject()) {
            Iterator<Map.Entry<String, JsonNode>> it = node.fields();
            while (it.hasNext()) {
                Map.Entry<String, JsonNode> entry = it.next();
                if ("".equals(entry.getValue().textValue())) {
                    entry.setValue(NullNode.getInstance());
                    continue;
                }

                jsonLeaf(entry.getValue());
            }
        }

        if (node.isArray()) {
            Iterator<JsonNode> it = node.iterator();
            while (it.hasNext()) {
                jsonLeaf(it.next());
            }
        }
    }
}

你可能感兴趣的:(java,json,开发语言)