jackson如何创建json对象和jackson工具类

由于阿里巴巴的fastjson经常爆出漏洞,需要频繁升级版本,单位研发部调研随后决定使用jackson作为json解析的工具,我就粗略研究了一下如何使用jackson创建中间json对象,大致测试如下(建供参考):

首先添加maven依赖:

		 <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.6</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
             <version>2.9.6</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
             <version>2.9.6</version>
        </dependency>
  • 构建json对象
 public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();

        ObjectNode rootNode = mapper.createObjectNode();

        ObjectNode childNode1 = mapper.createObjectNode();

        childNode1.put("name1","val1");

        childNode1.put("name2","val2");

        rootNode.set("obj1",childNode1);

        ObjectNode childNode2 = mapper.createObjectNode();

        childNode2.put("name3","val3");

        childNode2.put("name4","val4");

        rootNode.set("obj2",childNode2);

        ObjectNode childNode3 = mapper.createObjectNode();

        childNode3.put("name5","val5");

        childNode3.put("name6","val6");

        ArrayNode arrayNode = mapper.createArrayNode();
        arrayNode.add(childNode1);
        arrayNode.add(childNode2);
        arrayNode.add(childNode3);

        rootNode.set("obj3",childNode3);
        rootNode.set("obj4",arrayNode);


        String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);

        System.out.println(jsonString);

        ObjectNode jsonNodes = mapper.readValue(jsonString, ObjectNode.class);

        System.out.println(jsonNodes.get("obj4"));
        System.out.println(jsonNodes);

    }

输出结果:

{
  "obj1" : {
    "name1" : "val1",
    "name2" : "val2"
  },
  "obj2" : {
    "name3" : "val3",
    "name4" : "val4"
  },
  "obj3" : {
    "name5" : "val5",
    "name6" : "val6"
  },
  "obj4" : [ {
    "name1" : "val1",
    "name2" : "val2"
  }, {
    "name3" : "val3",
    "name4" : "val4"
  }, {
    "name5" : "val5",
    "name6" : "val6"
  } ]
}
[{"name1":"val1","name2":"val2"},{"name3":"val3","name4":"val4"},{"name5":"val5","name6":"val6"}]
{"obj1":{"name1":"val1","name2":"val2"},"obj2":{"name3":"val3","name4":"val4"},"obj3":{"name5":"val5","name6":"val6"},"obj4":[{"name1":"val1","name2":"val2"},{"name3":"val3","name4":"val4"},{"name5":"val5","name6":"val6"}]}


具体序列化工具大致封装了一下 如下:


import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JSONUtil {
    private static final Logger log = LoggerFactory.getLogger(JSONUtil.class);

    public JSONUtil() {
    }

    public static String toJSONString(Object data) {
        if (ObjectUtil.isEmpty(data)) {
            return "";
        } else {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setSerializationInclusion(Include.NON_NULL);
            objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
            objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);

            try {
                return objectMapper.writeValueAsString(data);
            } catch (JsonProcessingException var3) {
                log.error("JSONUtil.toJSONString.error", var3);
                return "";
            }
        }
    }

    public static <T> T parseObject(String jsonStr, Class<T> clazz) {
        if (ObjectUtil.isEmpty(jsonStr)) {
            return null;
        } else {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            try {
                return objectMapper.readValue(jsonStr, clazz);
            } catch (JsonProcessingException var4) {
                log.error("JSONUtil.parseObject.error", var4);
                return null;
            }
        }
    }

    public static <T> T parseObject(String jsonStr, TypeReference<T> valueTypeRef) {
        if (ObjectUtil.isEmpty(jsonStr)) {
            return null;
        } else {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            try {
                return objectMapper.readValue(jsonStr, valueTypeRef);
            } catch (Exception var4) {
                log.error("JSONUtil.parseObject.TypeReference.error", var4);
                return null;
            }
        }
    }

    public static <T> T parseSnakeObject(String json, Class<T> clazz) {
        if (ObjectUtil.isEmpty(json)) {
            return null;
        } else {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

            try {
                return objectMapper.readValue(json, clazz);
            } catch (JsonProcessingException var4) {
                log.error("JSONUtil.parseSnakeObject.error", var4);
                return null;
            }
        }
    }
}

自己查看需要的:更多大请移步官网看用法:jackson-core

上一篇:【SpringMVC】JSON使用(jackson、fastjson)


下一篇:Java技术类校招面试题汇总:python继承和java继承的区别