概述
Jackson框架是基于Java平台的一套数据处理工具,被称为“最好的Java Json解析器”。
Jackson Home Page:https://github.com/FasterXML/jackson
Jackson Wiki:http://wiki.fasterxml.com/JacksonHome
Jackson doc: https://github.com/FasterXML/jackson-docs
Jackson Download Page:http://wiki.fasterxml.com/JacksonDownload
依赖Jackson的三个核心库
jackson-core-2.5.3.jar
jackson-annotations-2.5.3.jar
jackson-databind-2.5.3.jar
maven引用Jackson
<dependency>
<groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.4</version> </dependency>
Jackson解析
package com.neusoft.bossAgent.utils; import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; @SuppressWarnings("unchecked") public class JSONUtils { private static final ObjectMapper mapper = new ObjectMapper(); private static final Logger log = LoggerFactory.getLogger(JSONUtils.class); static { mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);// mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setSerializationInclusion(Include.NON_NULL); } public static String toString(Object object) { String result = null; if (null == object) { return result; } try { result = mapper.writeValueAsString(object); } catch (JsonProcessingException e) { log.error("对象转换json字符串出错", e); } return result; } public static <T> T readValueFromString(Class<T> type, String value) { try { return (T) mapper.readValue(value, type); } catch (Exception e) { log.error("读取json字符串出错", e); } return null; } }
以下图片为objectmapper的一些配置