直接贴代码:

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&lt;List&lt;User&gt;&gt;);
* </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&lt;List&lt;User&gt;&gt;);
* </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工具类的更多相关文章

  1. 用jackson封装的JSON工具类

    package hjp.smart4j.framework.util; import com.fasterxml.jackson.databind.ObjectMapper; import org.s ...

  2. Java json工具类,jackson工具类,ObjectMapper工具类

    Java json工具类,jackson工具类,ObjectMapper工具类 >>>>>>>>>>>>>>> ...

  3. Code片段 : .properties属性文件操作工具类 & JSON工具类

    摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “贵专” — 泥瓦匠 一.java.util.Properties API & 案例 j ...

  4. JSON工具类的构建(后端版本)

    前言 在前后端交互的选择上,之前一直采用的是模板引擎(因为我只负责后端). 而这次的一个算是作业吧,前后端都是我,所以就研究了一下JSON交互在java web的应用(主要是前端). 优缺点 前后端耦 ...

  5. Json工具类,实现了反射将整个Object转换为Json对象的功能,支持Hibernate的延迟加

    package com.aherp.framework.util; import java.lang.reflect.Array;import java.lang.reflect.Method;imp ...

  6. Spring统一返回Json工具类,带分页信息

    前言: 项目做前后端分离时,我们会经常提供Json数据给前端,如果有一个统一的Json格式返回工具类,那么将大大提高开发效率和减低沟通成本. 此Json响应工具类,支持带分页信息,支持泛型,支持Htt ...

  7. 基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil

    基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil,把日常能用到的各种CRUD都进行了简化封装,让普通程序员只需关注业务即可,因为非常简单,故直接贴源代码,大家若需使用可以直 ...

  8. HttpClientUntils工具类的使用测试及注意事项(包括我改进的工具类和Controller端的注意事项【附 Json 工具类】)

    HttpClient工具类(我改过): package com.taotao.httpclient; import java.io.IOException; import java.net.URI; ...

  9. JSON工具类的构建(前端版本)

    前言 在前后端交互的选择上,之前一直采用的是模板引擎(因为我只负责后端). 而这次的一个算是作业吧,前后端都是我,所以就研究了一下JSON交互在java web的应用(主要是前端). 优缺点 因为我是 ...

随机推荐

  1. HTML5中script的async属性异步加载JS

    HTML5中script的async属性异步加载JS     HTML4.01为script标签定义了5个属性: charset 可选.指定src引入代码的字符集,大多数浏览器忽略该值.defer 可 ...

  2. EasyUI ComboBox默认值

    combobox数据加载完后设置默认值 $('#ck').combobox({ url: '/External/GetAllCk', valueField: 'Ddbh', textField: 'D ...

  3. 28.怎样在Swift中实现单例?

    1.回忆一下OC中的单例实现 //AFNetworkReachabilityManager中的单例,省略了其他代码 @interface AFNetworkReachabilityManager : ...

  4. ExtJs FormPanel布局

    FormPanel有两种布局:form和column,form是纵向布局,column为横向布局.默认为后者.使用layout属性定义布局类型.对于一个复杂的布局表单,最重要的是正确分割,分割结果直接 ...

  5. javascript第三方组件

    一.一个javascript文件上传组件.转载:http://www.cnblogs.com/fumj/archive/2012/12/07/2806673.html http://fineuploa ...

  6. SpinLock 自旋锁, CAS操作(Compare & Set) ABA Problem

    SpinLock 自旋锁 spinlock 用于CPU同步, 它的实现是基于CPU锁定数据总线的指令. 当某个CPU锁住数据总线后, 它读一个内存单元(spinlock_t)来判断这个spinlock ...

  7. Codeforces Round #310 (Div. 1) A. Case of Matryoshkas 水题

    C. String Manipulation 1.0 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contes ...

  8. linux C(hello world)三个数最大和三个数最新

  9. [AngularJS] Using Services in Angular Directives

    Directives have dependencies too, and you can use dependency injection to provide services for your ...

  10. MySQL Handler变量解析

      http://blog.itpub.net/29254281/viewspace-1159014/ To see the effect of a query do the following st ...