jsonUtil 工具类
2024-10-18 22:38:57
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;
} }
最新文章
- Windows Server 2008 R2常规安全设置及基本安全策略
- Java基础知识(壹)
- 绑定: x:Bind 绑定, x:Bind 绑定之 x:Phase, 使用绑定过程中的一些技巧
- Linux第五次实验
- lotusscript基本语法
- android 关于提高第三方app的service优先级
- [Qt5] 减少dll依赖和大小(特别是webkit的大小和依赖)
- PHP 做 RSA 签名 生成订单(支付宝例子)
- [转]Mac常用软件推荐
- 在PHP语言中使用JSON
- Ubuntu18.04安装mysql5.7
- 快速解决PHP调用Word组件DCOM权限的问题
- Difference Between InnoDb and MyISAM(个人觉着是好文章,简单易懂,推荐看)
- MYSQL的历史
- mac shell终端编辑命令行快捷键——行首,行尾
- 前缀和与差分之IncDec sequence
- VS编程,编辑WPF过程中,点击设计器中界面某一控件,在XAML中高亮突出显示相应的控件代码的设置方法。
- 2017-2018-2 20155225《网络对抗技术》实验一 PC平台逆向破解
- linux设置安全连接设置(私钥)
- Linux 下的jdk安装
热门文章
- mysql now() sysdate() curdate()区别
- hdu 2177(威佐夫博奕)
- hql查询语句 内存中的情况,fetch迫切查询关键字
- 【转】Linux下创建、销毁、使用 SWAP
- Selenium RC配置
- OpenGl从零开始之坐标变换(上)
- Pregel: A System for Large-Scale Graph Processing(译)
- 使用Eclipse的几个必须掌握的快捷方式(能力工场小马哥收集)
- 让git忽略ignore所有文件,只对某些文件进行版本控制
- 第三百四十四天 how can I 坚持