package com.zoe.optimus.service.message.mapper;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
import com.google.common.collect.Lists;
/**
* 简单封装Jackson,实现JSON String<->Java Object的Mapper.
* 封装不同的输出风格, 使用不同的builder函数创建实例.
* @author ThinkGem
* @version 2013-11-15
*/
public class JsonMapper extends ObjectMapper {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
private static JsonMapper mapper;
public JsonMapper() {
this(Include.ALWAYS);
}
public JsonMapper(Include include) {
// 设置输出时包含属性的风格
if (include != null) {
this.setSerializationInclusion(include);
}
// 允许单引号、允许不带引号的字段名称
this.enableSimple();
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 空值处理为空串
this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>(){
@Override
public void serialize(Object value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeString("");
}
});
// 进行HTML解码。
this.registerModule(new SimpleModule().addSerializer(String.class, new JsonSerializer<String>(){
@Override
public void serialize(String value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeString(StringEscapeUtils.unescapeHtml4(value));
}
}));
// 设置时区
this.setTimeZone(TimeZone.getDefault());//getTimeZone("GMT+8:00")
}
/**
* 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
*/
public static JsonMapper getInstance() {
if (mapper == null){
mapper = new JsonMapper().enableSimple();
}
return mapper;
}
/**
* 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
*/
public static JsonMapper nonDefaultMapper() {
if (mapper == null){
mapper = new JsonMapper(Include.NON_DEFAULT);
}
return mapper;
}
/**
* Object可以是POJO,也可以是Collection或数组。
* 如果对象为Null, 返回"null".
* 如果集合为空集合, 返回"[]".
*/
public String toJson(Object object) {
try {
return this.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(String jsonString, Class<T> clazz) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return this.readValue(jsonString, clazz);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 反序列化复杂Collection如List<Bean>, 先使用函數createCollectionType构造类型,然后调用本函数.
* @see #createCollectionType(Class, Class...)
*/
@SuppressWarnings("unchecked")
public <T> T fromJson(String jsonString, JavaType javaType) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return (T) this.readValue(jsonString, javaType);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 構造泛型的Collection Type如:
* ArrayList<MyBean>, 则调用constructCollectionType(ArrayList.class,MyBean.class)
* HashMap<String,MyBean>, 则调用(HashMap.class,String.class, MyBean.class)
*/
public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
return this.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
/**
* 當JSON裡只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性.
*/
@SuppressWarnings("unchecked")
public <T> T update(String jsonString, T object) {
try {
return (T) this.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);
}
return null;
}
/**
* 輸出JSONP格式數據.
*/
public String toJsonP(String functionName, Object object) {
return toJson(new JSONPObject(functionName, object));
}
/**
* 設定是否使用Enum的toString函數來讀寫Enum,
* 為False時時使用Enum的name()函數來讀寫Enum, 默認為False.
* 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用.
*/
public JsonMapper enableEnumUseToString() {
this.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
this.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
return this;
}
/**
* 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
* 默认会先查找jaxb的annotation,如果找不到再找jackson的。
*/
public JsonMapper enableJaxbAnnotation() {
JaxbAnnotationModule module = new JaxbAnnotationModule();
this.registerModule(module);
return this;
}
/**
* 允许单引号
* 允许不带引号的字段名称
*/
public JsonMapper enableSimple() {
this.configure(Feature.ALLOW_SINGLE_QUOTES, true);
this.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
return this;
}
/**
* 取出Mapper做进一步的设置或使用其他序列化API.
*/
public ObjectMapper getMapper() {
return this;
}
/**
* 对象转换为JSON字符串
* @param object
* @return
*/
public static String toJsonString(Object object){
return JsonMapper.getInstance().toJson(object);
}
/**
* JSON字符串转换为对象
* @param jsonString
* @param clazz
* @return
*/
public static Object fromJsonString(String jsonString, Class<?> clazz){
return JsonMapper.getInstance().fromJson(jsonString, clazz);
}
/**
* 测试
*/
public static void main(String[] args) {
List<Map<String, Object>> list = Lists.newArrayList();
// Map<String, Object> map = Maps.newHashMap();
// map.put("id", 1);
// map.put("pId", -1);
// map.put("name", "根节点");
// list.add(map);
// map = Maps.newHashMap();
// map.put("id", 2);
// map.put("pId", 1);
// map.put("name", null);
// map.put("open", true);
// list.add(map);
String json = JsonMapper.getInstance().toJson(list);
System.out.println(json);
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
zoe-optimus-service-message.zip (96个子文件)
zoe-optimus-service-message
.project 1KB
src
test
java
com
zoe
optimus
message
Publisher.java 2KB
TestChat.java 3KB
Receiver.java 2KB
main
webapp
WEB-INF
web.xml 2KB
common
jquery-1.12.4.js 297KB
index.html 3KB
resources
spring-context.xml 2KB
log4j2.xml 2KB
spring-context-cxf.xml 1KB
application.properties 880B
spring-context-db.xml 4KB
spring-mvc.xml 3KB
mybatis-config.xml 3KB
db.properties 321B
mappings
message
messageSql.xml 2KB
java
com
zoe
optimus
service
message
service
SendService.java 3KB
InternalMessageService.java 1KB
ReceiveBroker.java 6KB
exceptions
ConnectionException.java 456B
RegisterException.java 443B
LoginException.java 443B
ws
Dispatcher.java 2KB
annotation
MyBatisDao.java 806B
mapper
JsonMapper.java 8KB
dao
MessageDao.java 686B
web
MessageSocket.java 4KB
MessageEventController.java 3KB
util
IdUtils.java 647B
ClobUtil.java 2KB
PropertiesLoader.java 5KB
ValidUtil.java 7KB
SmackUtil.java 7KB
SpringContextHolder.java 1KB
DateUtils.java 4KB
entity
BaseEntity.java 325B
MessagePacket.java 1KB
ResultModel.java 2KB
DispatchParam.java 1KB
target
m2e-wtp
web-resources
META-INF
MANIFEST.MF 113B
maven
com.zoe
zoe-optimus-service-message
pom.properties 265B
pom.xml 25KB
classes
spring-context.xml 2KB
log4j2.xml 2KB
spring-context-cxf.xml 1KB
application.properties 880B
spring-context-db.xml 4KB
com
zoe
optimus
service
message
service
SendService.class 4KB
ReceiveBroker$1.class 1KB
ReceiveBroker.class 7KB
InternalMessageService.class 2KB
ReceiveBroker$1$1.class 2KB
exceptions
LoginException.class 413B
RegisterException.class 416B
ConnectionException.class 431B
ws
Dispatcher.class 2KB
annotation
MyBatisDao.class 566B
mapper
JsonMapper$2.class 2KB
JsonMapper.class 8KB
JsonMapper$1.class 1KB
dao
MessageDao.class 665B
web
MessageEventController.class 3KB
MessageSocket.class 4KB
util
ValidUtil.class 3KB
PropertiesLoader.class 4KB
ClobUtil.class 2KB
SpringContextHolder.class 1KB
DateUtils.class 4KB
SmackUtil.class 7KB
IdUtils.class 817B
entity
DispatchParam.class 1KB
ResultModel.class 2KB
MessagePacket.class 1KB
BaseEntity.class 361B
spring-mvc.xml 3KB
mybatis-config.xml 3KB
db.properties 321B
mappings
message
messageSql.xml 2KB
test-classes
com
zoe
optimus
message
Receiver$1.class 2KB
TestChat$1.class 909B
TestChat.class 5KB
Publisher.class 2KB
Receiver.class 2KB
TestChat$1$1.class 1KB
.settings
org.eclipse.wst.jsdt.ui.superType.container 49B
org.eclipse.wst.common.project.facet.core.xml 346B
org.eclipse.m2e.core.prefs 90B
org.eclipse.jdt.core.prefs 736B
org.eclipse.wst.validation.prefs 50B
org.eclipse.wst.jsdt.ui.superType.name 6B
org.eclipse.wst.common.project.facet.core.prefs.xml 321B
org.eclipse.core.resources.prefs 155B
org.eclipse.wst.common.component 737B
.jsdtscope 639B
pom.xml 25KB
.classpath 1KB
共 96 条
- 1
betalot
- 粉丝: 2
- 资源: 3
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
前往页