分享一个关于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的应用(主要是前端). 优缺点 因为我是 ...
随机推荐
- android 获取手机型号,本机电话号码,SDK版本以及firmwarw版本号(即系统版本号)
Android开发平台中,可通过TelephonyManager 获取本机号码. TelephonyManager phoneMgr=(TelephonyManager)this.getSystemS ...
- 如何在我们项目中利用开源的图表(js chart)
最近觉得应该把自己在技术上的一些心得记录在博客里面跟大家分享,一起讨论,一起成长! 这篇随笔主要为介绍chart在项目中的运用,因为在我们看到一些开源的chart时候,是使 ...
- xx.exe 中的 0x7c92e4df 处最可能的异常: 0xC0000008: An invalid handle was specified
今天遇到个超级奇怪的问题,昨天还好端端的程序,今天用VS打开后,在关闭主窗口的时候居然弹出错误提示:xx.exe 中的 0x7c92e4df 处最可能的异常: "0xC0000008: An ...
- IE6中奇数宽高的BUG
一个外部的相对定位div,内部一个绝对定位的div(right:0), 如图: 可是在IE6下查看,却变成了right:1px的效果了: IE6还有奇数宽高的bug,解决方案就是将外部相对定位的div ...
- 【转】工科男IT职场求生法则
转自:http://www.36dsj.com/archives/3459 我在IT职场打滚超过10年了,从小小的程序员做到常务副总.相对于其它行业,IT职场应该算比较光明的了,但也陷阱重重,本文说说 ...
- This is your life , in Winbledon , interview Roger Federer
http://v.youku.com/v_show/id_XNTc2Nzg5MTMy.html?firsttime=119 Roger Federer this is you life how mu ...
- 保持长宽比 对背景图像进行修改android:scaleType="fitXY"
关于android中ImageView的外观,即图片在其内显示出的样子,与布局文件中adjustViewBonds和scaleType属性的关系.我进行了一些探索.现跟大家共享,欢迎各位指教.分别将a ...
- [Angular 2] Order Dynamic Components Inside an Angular 2 ViewContainer
By default, when you generate components, they will simply be added to the page in order, one after ...
- Android典型界面设计——ViewPage+Fragment实现区域顶部tab滑动切换
一.问题描写叙述 本系列将结合案例应用,陆续向大家介绍一些Android典型界面的设计,首先说说tab导航,导航分为一层和两层(底部区块+区域内头部导航).主要实现方案有RadioGroup+View ...
- SQL Server 2008 清空删除日志文件
USE [master]GOALTER DATABASE STAR9SQL SET RECOVERY SIMPLE WITH NO_WAITGOALTER DATABASE STAR9SQL SET ...