Jackson处理json,xml,csv
可以方便地实现序列化和反序列化,实现三者互转以及java bean互转
maven依赖
com.fasterxml.jackson.core jackson-core 2.6.3 com.fasterxml.jackson.core jackson-databind 2.6.3 com.fasterxml.jackson.core jackson-annotations 2.6.3 com.fasterxml.jackson.dataformat jackson-dataformat-csv 2.7.3 com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.7.3 org.codehaus.woodstox woodstox-core-asl 4.4.1
Xml工具类
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class XmlUtil {
private static final Logger logger = LogManager.getLogger(XmlUtil.class);
private static final XmlMapper xmlMapper = new XmlMapper();
private XmlUtil() {
}
/**
* 输出全部属性 如果xml中存在,对象中没有,则自动忽略该属性 失败返回null
*
* @param xmlContent
* @param clazz
* @return
*/
public static T toNormalObject(String xmlContent, Class clazz) {
return xmlToObject(xmlContent, clazz);
}
/**
* 输出全部属性
* 如果xml中存在,对象中没有,则自动忽略该属性
* 失败返回null
* @param inputStream
* @param clazz
* @return
*/
public static T toNormalObject(byte[] bytes, Class clazz) {
return xmlToObject(bytes, clazz);
}
/**
* 输出全部属性 失败返回""
*
* @param object
* @return
*/
public synchronized static byte[] toNormalXml(Object object) {
return objectToXml(Include.ALWAYS, object);
}
private static T xmlToObject(byte[] bytes, Class clazz) {
try {
return xmlMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(bytes, clazz);
} catch (Exception e) {
logger.info("XmlToObject failed:", e);
}
return null;
}
private static T xmlToObject(String xmlContent, Class clazz) {
try {
return xmlMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(xmlContent, clazz);
} catch (Exception e) {
logger.info("XmlToObject failed:", e);
}
return null;
}
private static byte[] objectToXml(Include include, T object) {
try {
return xmlMapper.setSerializationInclusion(include).writerWithDefaultPrettyPrinter().writeValueAsBytes(object);
} catch (JsonProcessingException e) {
logger.info("ObjToXml failed:", e);
}
return null;
}
}
Csv工具类
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
public class CsvUtil {
private static final Logger logger = LogManager.getLogger(CsvUtil.class);
private static final CsvMapper csvMapper = new CsvMapper();
private CsvUtil(){
}
/**
* 输出全部属性
* 如果csv中存在,对象中没有,则自动忽略该属性
* 失败返回null
*
* @param csvContent
* @param clazz
* @return
*/
public static List toNormalObject(String csvContent, Class clazz) {
try {
CsvSchema schema = CsvSchema.emptySchema().withHeader();
MappingIterator mappingIterator = csvMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readerFor(clazz).with(schema).readValues(csvContent);
return mappingIterator.readAll();
} catch (Exception e) {
logger.info("CsvToObject failed:", e);
}
return null;
}
/**
* 输出全部属性
* 如果csv中存在,对象中没有,则自动忽略该属性
* 失败返回null
* @param inputStream
* @param clazz
* @return
*/
public synchronized static List toNormalObject(byte[] bytes, Class clazz) {
try {
CsvSchema schema = CsvSchema.emptySchema().withHeader();
MappingIterator mappingIterator = csvMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readerFor(clazz).with(schema).readValues(bytes);
return mappingIterator.readAll();
} catch (Exception e) {
logger.info("CsvToObject failed:", e);
}
return null;
}
/**
* 输出全部属性 失败返回""
*
* @param object
* @return
*/
public static String toNormalCsv(Object object) {
return objectToCsv(Include.ALWAYS, object);
}
private static String objectToCsv(Include include, T object) {
try {
CsvSchema csvSchema = csvMapper.schemaFor(object.getClass());
return csvMapper.setSerializationInclusion(include).writer(csvSchema).writeValueAsString(object);
} catch (JsonProcessingException e) {
logger.info("ObjToCsv failed:", e);
}
return "";
}
}
Json工具类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil {
private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
private static ObjectMapper objectMapper = new ObjectMapper();
/**
* 输出全部属性
* 失败返回""
* @param object
* @return
*/
public static String toNormalJson(Object object) {
return toJson(Include.ALWAYS, object);
}
/**
* 输出非空属性
* 失败返回""
* @param object
* @return
*/
public static String toNonNullJson(Object object) {
return toJson(Include.NON_NULL, object);
}
/**
* 输出非Null且非Empty(如List.isEmpty)的属性
* 失败返回""
* @param object
* @return
*/
public static String toNonEmptyJson(Object object) {
return toJson(Include.NON_EMPTY, object);
}
/**
* 转成Json
* @param include
* @param object
* @return
*/
private static String toJson(Include include, Object object) {
try {
objectMapper.setSerializationInclusion(include);
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
logger.info("Obj转Json报错:", e);
}
return "";
}
/**
* 输出全部属性
* 如果json中存在,对象中没有,则自动忽略该属性
* 失败返回null
*
* @param json
* @param clazz
* @return
*/
public static T toNormalObject(String json, Class clazz) {
return toObject(json, clazz);
}
/**
* 转成Object
* @param include
* @param json
* @param clazz
* @return
*/
private static T toObject(String json, Class clazz) {
try {
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
return objectMapper.readValue(json, clazz);
} catch (Exception e) {
logger.info("Json转Obj报错:", e);
}
return null;
}
}
Java bean实体类(get set省略)
csv使用@JsonProperty来注解csv文件的列名
xml使用@JacksonXmlProperty来注解xml的属性
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
public class CsvItem {
@JacksonXmlProperty(localName = "Label")
@JsonProperty("Display Name")
private String label;
@JacksonXmlProperty(localName = "ValueType")
@JsonProperty
private String valueType;
@JacksonXmlProperty(localName = "Editable")
@JsonProperty("Editable")
private String editable;
@JacksonXmlProperty(localName = "Required")
@JsonProperty("Required")
private String required;
}
import java.util.List;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
@JacksonXmlRootElement(localName = "Page")
public class CsvPage {
@JacksonXmlElementWrapper(useWrapping = false)
@JacksonXmlProperty(localName = "Item")
private List csvItems;
public CsvPage() {
}
public CsvPage(List csvItems) {
this.csvItems = csvItems;
}
public List getCsvItems() {
return csvItems;
}
public void setCsvItems(List csvItems) {
this.csvItems = csvItems;
}
}
注意scv需要设置schema也就是csv文件的列名
public static List toNormalObject(byte[] bytes, Class clazz) throws JsonProcessingException, IOException {
CsvSchema schema = CsvSchema.emptySchema().withHeader();
MappingIterator mappingIterator = csvMapper
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.readerFor(clazz).with(schema).readValues(bytes);
return mappingIterator.readAll();
}
xml文件如果需要格式化输出
xmlMapper.setSerializationInclusion(include).writerWithDefaultPrettyPrinter().writeValueAsBytes(object);
writerWithDefaultPrettyPrinter需要依赖
org.codehaus.woodstox woodstox-core-asl
例子中的xml文件
true true false false
例子中的csv文件
Display Name,Editable,Required
Account,TRUE,TRUE
Outstanding,FALSE,FALSE
例子中csv文件有三个属性xml有四个属性,所以xml中
由于Jackson处理Json内容比较多
下一篇有时间再详细说明
以上