分享一个关于jackson的Json工具类
直接贴代码:
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.TypeReference; import java.io.IOException;
import java.text.SimpleDateFormat; /**
* JSON的工具类
*
* <h3>Here is an example:</h3>
*
* <pre>
* // 将json通过类型转换成对象
* {@link JsonUtil JsonUtil}.fromJson("{\"username\":\"username\", \"password\":\"password\"}", User.class);
* </pre>
* <hr />
* <pre>
* // 传入转换的引用类型
* {@link JsonUtil JsonUtil}.fromJson("[{\"username\":\"username\", \"password\":\"password\"}, {\"username\":\"username\", \"password\":\"password\"}]", new TypeReference<List<User>>);
* </pre>
* <hr />
* <pre>
* // 将对象转换成json
* {@link JsonUtil JsonUtil}.toJson(user);
* </pre>
* <hr />
* <pre>
* // 将对象转换成json, 可以设置输出属性
* {@link JsonUtil JsonUtil}.toJson(user, {@link Inclusion Inclusion.ALWAYS});
* </pre>
* <hr />
* <pre>
* // 将对象转换成json, 传入配置对象
* {@link ObjectMapper ObjectMapper} mapper = new ObjectMapper();
* mapper.setSerializationInclusion({@link Inclusion Inclusion.ALWAYS});
* mapper.configure({@link Feature Feature.FAIL_ON_UNKNOWN_PROPERTIES}, false);
* mapper.configure({@link Feature Feature.FAIL_ON_NUMBERS_FOR_ENUMS}, true);
* mapper.setDateFormat(new {@link SimpleDateFormat SimpleDateFormat}("yyyy-MM-dd HH:mm:ss"));
* {@link JsonUtil JsonUtil}.toJson(user, mapper);
* </pre>
* <hr />
* <pre>
* // 获取Mapper对象
* {@link JsonUtil JsonUtil}.mapper();
* </pre>
*
* @see JsonUtil JsonUtil
* @see Feature Feature
* @see ObjectMapper ObjectMapper
* @see Inclusion Inclusion
* @see IOException IOException
* @see SimpleDateFormat SimpleDateFormat
*
*/
@SuppressWarnings("unchecked")
public final class JsonUtil { private static ObjectMapper MAPPER; static {
MAPPER = generateMapper(Inclusion.ALWAYS);
} private JsonUtil() {
} /**
* 将json通过类型转换成对象
*
* <pre>
* {@link JsonUtil JsonUtil}.fromJson("{\"username\":\"username\", \"password\":\"password\"}", User.class);
* </pre>
*
* @param json json字符串
* @param clazz 泛型类型
* @return 返回对象
* @throws IOException
*/
public static <T> T fromJson(String json, Class<T> clazz) throws IOException {
return clazz.equals(String.class) ? (T) json : MAPPER.readValue(json, clazz);
} /**
* 将json通过类型转换成对象
*
* <pre>
* {@link JsonUtil JsonUtil}.fromJson("[{\"username\":\"username\", \"password\":\"password\"}, {\"username\":\"username\", \"password\":\"password\"}]", new TypeReference<List<User>>);
* </pre>
*
* @param json json字符串
* @param typeReference 引用类型
* @return 返回对象
* @throws IOException
*/
public static <T> T fromJson(String json, TypeReference<?> typeReference) throws IOException {
return (T) (typeReference.getType().equals(String.class) ? json : MAPPER.readValue(json, typeReference));
} /**
* 将对象转换成json
*
* <pre>
* {@link JsonUtil JsonUtil}.toJson(user);
* </pre>
*
* @param src 对象
* @return 返回json字符串
* @throws IOException
*/
public static <T> String toJson(T src) throws IOException {
return src instanceof String ? (String) src : MAPPER.writeValueAsString(src);
} /**
* 将对象转换成json, 可以设置输出属性
*
* <pre>
* {@link JsonUtil JsonUtil}.toJson(user, {@link Inclusion Inclusion.ALWAYS});
* </pre>
*
* {@link Inclusion Inclusion 对象枚举}
* <ul>
* <li>{@link Inclusion Inclusion.ALWAYS 全部列入}</li>
* <li>{@link Inclusion Inclusion.NON_DEFAULT 字段和对象默认值相同的时候不会列入}</li>
* <li>{@link Inclusion Inclusion.NON_EMPTY 字段为NULL或者""的时候不会列入}</li>
* <li>{@link Inclusion Inclusion.NON_NULL 字段为NULL时候不会列入}</li>
* </ul>
*
* @param src 对象
* @param inclusion 传入一个枚举值, 设置输出属性
* @return 返回json字符串
* @throws IOException
*/
public static <T> String toJson(T src, Inclusion inclusion) throws IOException {
if (src instanceof String) {
return (String) src;
} else {
ObjectMapper customMapper = generateMapper(inclusion);
return customMapper.writeValueAsString(src);
}
} /**
* 将对象转换成json, 传入配置对象
*
* <pre>
* {@link ObjectMapper ObjectMapper} mapper = new ObjectMapper();
* mapper.setSerializationInclusion({@link Inclusion Inclusion.ALWAYS});
* mapper.configure({@link Feature Feature.FAIL_ON_UNKNOWN_PROPERTIES}, false);
* mapper.configure({@link Feature Feature.FAIL_ON_NUMBERS_FOR_ENUMS}, true);
* mapper.setDateFormat(new {@link SimpleDateFormat SimpleDateFormat}("yyyy-MM-dd HH:mm:ss"));
* {@link JsonUtil JsonUtil}.toJson(user, mapper);
* </pre>
*
* {@link ObjectMapper ObjectMapper}
*
* @see ObjectMapper
*
* @param src 对象
* @param mapper 配置对象
* @return 返回json字符串
* @throws IOException
*/
public static <T> String toJson(T src, ObjectMapper mapper) throws IOException {
if (null != mapper) {
if (src instanceof String) {
return (String) src;
} else {
return mapper.writeValueAsString(src);
}
} else {
return null;
}
} /**
* 返回{@link ObjectMapper ObjectMapper}对象, 用于定制性的操作
*
* @return {@link ObjectMapper ObjectMapper}对象
*/
public static ObjectMapper mapper() {
return MAPPER;
} /**
* 通过Inclusion创建ObjectMapper对象
*
* {@link Inclusion Inclusion 对象枚举}
* <ul>
* <li>{@link Inclusion Inclusion.ALWAYS 全部列入}</li>
* <li>{@link Inclusion Inclusion.NON_DEFAULT 字段和对象默认值相同的时候不会列入}</li>
* <li>{@link Inclusion Inclusion.NON_EMPTY 字段为NULL或者""的时候不会列入}</li>
* <li>{@link Inclusion Inclusion.NON_NULL 字段为NULL时候不会列入}</li>
* </ul>
*
* @param inclusion 传入一个枚举值, 设置输出属性
* @return 返回ObjectMapper对象
*/
private static ObjectMapper generateMapper(Inclusion inclusion) { ObjectMapper customMapper = new ObjectMapper(); // 设置输出时包含属性的风格
customMapper.setSerializationInclusion(inclusion); // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
customMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 禁止使用int代表Enum的order()來反序列化Enum,非常危險
customMapper.configure(Feature.FAIL_ON_NUMBERS_FOR_ENUMS, true); // 所有日期格式都统一为以下样式
customMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); return customMapper;
}
}
分享一个关于jackson的Json工具类的更多相关文章
- 用jackson封装的JSON工具类
package hjp.smart4j.framework.util; import com.fasterxml.jackson.databind.ObjectMapper; import org.s ...
- Java json工具类,jackson工具类,ObjectMapper工具类
Java json工具类,jackson工具类,ObjectMapper工具类 >>>>>>>>>>>>>>> ...
- Code片段 : .properties属性文件操作工具类 & JSON工具类
摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “贵专” — 泥瓦匠 一.java.util.Properties API & 案例 j ...
- JSON工具类的构建(后端版本)
前言 在前后端交互的选择上,之前一直采用的是模板引擎(因为我只负责后端). 而这次的一个算是作业吧,前后端都是我,所以就研究了一下JSON交互在java web的应用(主要是前端). 优缺点 前后端耦 ...
- Json工具类,实现了反射将整个Object转换为Json对象的功能,支持Hibernate的延迟加
package com.aherp.framework.util; import java.lang.reflect.Array;import java.lang.reflect.Method;imp ...
- Spring统一返回Json工具类,带分页信息
前言: 项目做前后端分离时,我们会经常提供Json数据给前端,如果有一个统一的Json格式返回工具类,那么将大大提高开发效率和减低沟通成本. 此Json响应工具类,支持带分页信息,支持泛型,支持Htt ...
- 基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil
基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil,把日常能用到的各种CRUD都进行了简化封装,让普通程序员只需关注业务即可,因为非常简单,故直接贴源代码,大家若需使用可以直 ...
- HttpClientUntils工具类的使用测试及注意事项(包括我改进的工具类和Controller端的注意事项【附 Json 工具类】)
HttpClient工具类(我改过): package com.taotao.httpclient; import java.io.IOException; import java.net.URI; ...
- JSON工具类的构建(前端版本)
前言 在前后端交互的选择上,之前一直采用的是模板引擎(因为我只负责后端). 而这次的一个算是作业吧,前后端都是我,所以就研究了一下JSON交互在java web的应用(主要是前端). 优缺点 因为我是 ...
随机推荐
- 使用IBatisNet的网站,修改database.config无效的问题解决
这周五去客户那更新了一个使用了IBatisNet的Web项目,备份了项目.数据库之后,替换更新的文件(含bin目录)却报数据库连接错. 因为是接手的一个维护项目,加上交接有点问题,所以遇到问题只能自己 ...
- Apache Kafka:下一代分布式消息系统
[http://www.infoq.com/cn/articles/apache-kafka/]分布式发布-订阅消息系统. Kafka是一种快速.可扩展的.设计内在就是分布式的,分区的和可复制的提交日 ...
- SVN安装与使用
来自:http://www.cnblogs.com/xiaobaihome/archive/2012/03/20/2407610.html SVN服务器搭建和使用(一) Subversion是优秀的版 ...
- cocos2d-x 如何保持屏幕常亮
转自:http://blog.csdn.net/wolfking_2009/article/details/8939027 貌似cocos2d-x没有接口直接做这个功能 而各个平台又不一样,所以只能对 ...
- TAxThread - Inter thread message based communication - Delphi
http://www.cybletter.com/index.php?id=3 http://www.cybletter.com/index.php?id=30 Source Code http:// ...
- linux系统命令解析(0基础篇)
经常使用命令 ctrl+W+T 当进入gvim文档编辑界面后,假设是C文件,能够列出当前文件里的全部函数. Shift+* 当进入gvim文档编辑页面,能够搜索当前keyword. ech ...
- uva 11324 The Largest Clique(强连通分量缩点+DAG动态规划)
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=25&page=sh ...
- eclipse添加第三方源码
- Wunder Fund Round 2016 (Div. 1 + Div. 2 combined) A. Slime Combining 水题
A. Slime Combining 题目连接: http://www.lydsy.com/JudgeOnline/problem.php?id=2768 Description Your frien ...
- 【摘要】获得HTML元素的绝对位置
function findAbsolutePosition(obj) { var curleft = curtop = 0; if (obj.offsetParent) { do { curleft ...