提交 8719eed3 编写于 作者: C calvin1978

恢复jsonMapper 与 XmlMapper

上级 cda22531
......@@ -14,6 +14,7 @@
<slf4j.version>1.7.25</slf4j.version>
<logback.version>1.1.8</logback.version>
<dozer.version>5.5.1</dozer.version>
<jackson.version>2.8.6</jackson.version>
<junit.version>4.12</junit.version>
<assertj.version>2.6.0</assertj.version>
<mockito.version>1.10.19</mockito.version>
......@@ -53,6 +54,15 @@
<artifactId>dozer</artifactId>
<version>${dozer.version}</version>
</dependency>
<!-- for JsonMapper -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
<optional>true</optional>
</dependency>
<!-- TEST begin -->
<dependency>
......
package org.springside.modules.utils.mapper;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springside.modules.utils.base.annotation.Nullable;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.JSONPObject;
/**
* 简单封装Jackson,实现JSON String<->Java Object转换的Mapper.
*
* 可以直接使用公共示例JsonMapper.INSTANCE, 也可以使用不同的builder函数创建实例,封装不同的输出风格,
*
* 不要使用GSON, 在对象稍大时非常缓慢.
*
* 注意: 需要参考本模块的POM文件,显式引用jackson.
*
* @author calvin
*/
public class JsonMapper {
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
public static final JsonMapper INSTANCE = new JsonMapper();
private ObjectMapper mapper;
public JsonMapper() {
this(null);
}
public JsonMapper(Include include) {
mapper = new ObjectMapper();
// 设置输出时包含属性的风格
if (include != null) {
mapper.setSerializationInclusion(include);
}
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
/**
* 创建只输出非Null的属性到Json字符串的Mapper.
*/
public static JsonMapper nonNullMapper() {
return new JsonMapper(Include.NON_NULL);
}
/**
* 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper.
*
* 注意,要小心使用, 特别留意empty的情况.
*/
public static JsonMapper nonEmptyMapper() {
return new JsonMapper(Include.NON_EMPTY);
}
/**
* 默认的全部输出的Mapper, 区别于INSTANCE,可以做进一步的配置
*/
public static JsonMapper defaultMapper() {
return new JsonMapper();
}
/**
* Object可以是POJO,也可以是Collection或数组。 如果对象为Null, 返回"null". 如果集合为空集合, 返回"[]".
*/
public String toJson(Object object) {
try {
return mapper.writeValueAsString(object);
} catch (IOException e) {
logger.warn("write to json string error:" + object, e);
return null;
}
}
/**
* 反序列化POJO或简单Collection如List<String>.
*
* 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合.
*
* 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String, JavaType)
*
* @see #fromJson(String, JavaType)
*/
public <T> T fromJson(@Nullable String jsonString, Class<T> clazz) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return mapper.readValue(jsonString, clazz);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 反序列化复杂Collection如List<Bean>, contructCollectionType()或contructMapType()构造类型, 然后调用本函数.
*
* @see #createCollectionType(Class, Class...)
*/
public <T> T fromJson(@Nullable String jsonString, JavaType javaType) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return (T) mapper.readValue(jsonString, javaType);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 构造Collection类型.
*/
public JavaType buildCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass) {
return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
}
/**
* 构造Map类型.
*/
public JavaType buildMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass) {
return mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
}
/**
* 当JSON里只含有Bean的部分属性時,更新一個已存在Bean,只覆盖該部分的属性.
*/
public void update(String jsonString, Object object) {
try {
mapper.readerForUpdating(object).readValue(jsonString);
} catch (JsonProcessingException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
} catch (IOException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
}
}
/**
* 輸出JSONP格式數據.
*/
public String toJsonP(String functionName, Object object) {
return toJson(new JSONPObject(functionName, object));
}
/**
* 設定是否使用Enum的toString函數來讀寫Enum, 為False時時使用Enum的name()函數來讀寫Enum, 默認為False. 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用.
*/
public void enableEnumUseToString() {
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
}
/**
* 取出Mapper做进一步的设置或使用其他序列化API.
*/
public ObjectMapper getMapper() {
return mapper;
}
}
/*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package org.springside.modules.utils.mapper;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.springside.modules.utils.base.ExceptionUtil;
import org.springside.modules.utils.reflect.ClassUtil;
/**
* 使用Jaxb2.0实现XML<->Java Object的Mapper.
*
* 在创建时需要设定所有需要序列化的Root对象的Class.
* 特别支持Root对象是Collection的情形.
*
* @author calvin
*/
public class XmlMapper {
private static ConcurrentMap<Class, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class, JAXBContext>();
/**
* Java Object->Xml without encoding.
*/
public static String toXml(Object root) {
Class clazz =ClassUtil.unwrapCglib(root);
return toXml(root, clazz, null);
}
/**
* Java Object->Xml with encoding.
*/
public static String toXml(Object root, String encoding) {
Class clazz = ClassUtil.unwrapCglib(root);
return toXml(root, clazz, encoding);
}
/**
* Java Object->Xml with encoding.
*/
public static String toXml(Object root, Class clazz, String encoding) {
try {
StringWriter writer = new StringWriter();
createMarshaller(clazz, encoding).marshal(root, writer);
return writer.toString();
} catch (JAXBException e) {
throw ExceptionUtil.unchecked(e);
}
}
/**
* Java Collection->Xml without encoding, 特别支持Root Element是Collection的情形.
*/
public static String toXml(Collection<?> root, String rootName, Class clazz) {
return toXml(root, rootName, clazz, null);
}
/**
* Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形.
*/
public static String toXml(Collection<?> root, String rootName, Class clazz, String encoding) {
try {
CollectionWrapper wrapper = new CollectionWrapper();
wrapper.collection = root;
JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(new QName(rootName),
CollectionWrapper.class, wrapper);
StringWriter writer = new StringWriter();
createMarshaller(clazz, encoding).marshal(wrapperElement, writer);
return writer.toString();
} catch (JAXBException e) {
throw ExceptionUtil.unchecked(e);
}
}
/**
* Xml->Java Object.
*/
public static <T> T fromXml(String xml, Class<T> clazz) {
try {
StringReader reader = new StringReader(xml);
return (T) createUnmarshaller(clazz).unmarshal(reader);
} catch (JAXBException e) {
throw ExceptionUtil.unchecked(e);
}
}
/**
* 创建Marshaller并设定encoding(可为null).
* 线程不安全,需要每次创建或pooling。
*/
public static Marshaller createMarshaller(Class clazz, String encoding) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
if (StringUtils.isNotBlank(encoding)) {
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
}
return marshaller;
} catch (JAXBException e) {
throw ExceptionUtil.unchecked(e);
}
}
/**
* 创建UnMarshaller.
* 线程不安全,需要每次创建或pooling。
*/
public static Unmarshaller createUnmarshaller(Class clazz) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
return jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
throw ExceptionUtil.unchecked(e);
}
}
protected static JAXBContext getJaxbContext(Class clazz) {
Validate.notNull(clazz, "'clazz' must not be null");
JAXBContext jaxbContext = jaxbContexts.get(clazz);
if (jaxbContext == null) {
try {
jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
jaxbContexts.putIfAbsent(clazz, jaxbContext);
} catch (JAXBException ex) {
throw new RuntimeException("Could not instantiate JAXBContext for class [" + clazz + "]: "
+ ex.getMessage(), ex);
}
}
return jaxbContext;
}
/**
* 封装Root Element 是 Collection的情况.
*/
public static class CollectionWrapper {
@XmlAnyElement
protected Collection<?> collection;
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册