欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

关于Jackson的使用说明

程序员文章站 2022-06-01 08:30:05
...

概述

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的一些配置


关于Jackson的使用说明

相关标签: jackson json