package org.konghao.basic.util;

 import java.io.IOException;
import java.io.StringWriter; import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper; public class JsonUtil {
private static JsonUtil ju;
private static JsonFactory jf;
private static ObjectMapper mapper; private JsonUtil() {
} public static JsonUtil getInstance() {
if (ju == null)
ju = new JsonUtil();
return ju;
} public static ObjectMapper getMapper() {
if (mapper == null) {
mapper = new ObjectMapper();
}
return mapper;
} public static JsonFactory getFactory() {
if (jf == null)
jf = new JsonFactory();
return jf;
} public String obj2json(Object obj) {
JsonGenerator jg = null;
try {
jf = getFactory();
mapper = getMapper();
StringWriter out = new StringWriter();
jg = jf.createJsonGenerator(out);
mapper.writeValue(jg, obj);
return out.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (jg != null)
jg.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
} public Object json2obj(String json, Class<?> clz) {
try {
mapper = getMapper();
return mapper.readValue(json, clz);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} }

最新文章

  1. Windows Server 2008 R2常规安全设置及基本安全策略
  2. Java基础知识(壹)
  3. 绑定: x:Bind 绑定, x:Bind 绑定之 x:Phase, 使用绑定过程中的一些技巧
  4. Linux第五次实验
  5. lotusscript基本语法
  6. android 关于提高第三方app的service优先级
  7. [Qt5] 减少dll依赖和大小(特别是webkit的大小和依赖)
  8. PHP 做 RSA 签名 生成订单(支付宝例子)
  9. [转]Mac常用软件推荐
  10. 在PHP语言中使用JSON
  11. Ubuntu18.04安装mysql5.7
  12. 快速解决PHP调用Word组件DCOM权限的问题
  13. Difference Between InnoDb and MyISAM(个人觉着是好文章,简单易懂,推荐看)
  14. MYSQL的历史
  15. mac shell终端编辑命令行快捷键——行首,行尾
  16. 前缀和与差分之IncDec sequence
  17. VS编程,编辑WPF过程中,点击设计器中界面某一控件,在XAML中高亮突出显示相应的控件代码的设置方法。
  18. 2017-2018-2 20155225《网络对抗技术》实验一 PC平台逆向破解
  19. linux设置安全连接设置(私钥)
  20. Linux 下的jdk安装

热门文章

  1. mysql now() sysdate() curdate()区别
  2. hdu 2177(威佐夫博奕)
  3. hql查询语句 内存中的情况,fetch迫切查询关键字
  4. 【转】Linux下创建、销毁、使用 SWAP
  5. Selenium RC配置
  6. OpenGl从零开始之坐标变换(上)
  7. Pregel: A System for Large-Scale Graph Processing(译)
  8. 使用Eclipse的几个必须掌握的快捷方式(能力工场小马哥收集)
  9. 让git忽略ignore所有文件,只对某些文件进行版本控制
  10. 第三百四十四天 how can I 坚持