json解析工具类
对jackson的ObjectMapper的封装:
ObjectMapperUtils:
import static com.fasterxml.jackson.core.JsonFactory.Feature.INTERN_FIELD_NAMES;
import static com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_COMMENTS;
import static com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS;
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
import static com.fasterxml.jackson.databind.type.TypeFactory.defaultInstance; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Map; import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.fasterxml.jackson.module.kotlin.KotlinModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import com.hubspot.jackson.datatype.protobuf.ProtobufModule; public final class ObjectMapperUtils { private static final String EMPTY_JSON = "{}"; private static final String EMPTY_ARRAY_JSON = "[]"; /**
* disable INTERN_FIELD_NAMES, 解决GC压力大、内存泄露的问题
*/
private static final ObjectMapper MAPPER = new ObjectMapper(new JsonFactory().disable(INTERN_FIELD_NAMES))
.registerModule(new GuavaModule()); static {
MAPPER.disable(FAIL_ON_UNKNOWN_PROPERTIES);
MAPPER.enable(ALLOW_UNQUOTED_CONTROL_CHARS);
MAPPER.enable(ALLOW_COMMENTS);
MAPPER.registerModule(new ParameterNamesModule());
MAPPER.registerModule(new KotlinModule());
MAPPER.registerModule(new ProtobufModule());
} public static String toJSON(@Nullable Object obj) {
if (obj == null) {
return null;
}
try {
return MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
} /**
* 输出格式化好的json
* 请不要在输出log时使用
* <p>
* 一般只用于写结构化数据到ZooKeeper时使用(为了更好的可读性)
*/
public static String toPrettyJson(@Nullable Object obj) {
if (obj == null) {
return null;
}
try {
return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
} public static void toJSON(@Nullable Object obj, OutputStream writer) {
if (obj == null) {
return;
}
try {
MAPPER.writeValue(writer, obj);
} catch (IOException e) {
throw new RuntimeException(e);
}
} public static <T> T fromJSON(@Nullable byte[] bytes, Class<T> valueType) {
if (bytes == null) {
return null;
}
try {
return MAPPER.readValue(bytes, valueType);
} catch (IOException e) {
throw new RuntimeException(e);
}
} public static <T> T fromJSON(@Nullable String json, Class<T> valueType) {
if (json == null) {
return null;
}
try {
return MAPPER.readValue(json, valueType);
} catch (IOException e) {
throw new RuntimeException(e);
}
} public static <T> T fromJSON(Object value, Class<T> valueType) {
if (value == null) {
return null;
} else if (value instanceof String) {
return fromJSON((String) value, valueType);
} else if (value instanceof byte[]) {
return fromJSON((byte[]) value, valueType);
} else {
return null;
}
} public static <T> T value(Object rawValue, Class<T> type) {
return MAPPER.convertValue(rawValue, type);
} public static <T> T update(T rawValue, String newProperty) {
try {
return MAPPER.readerForUpdating(rawValue).readValue(newProperty);
} catch (IOException e) {
throw new RuntimeException(e);
}
} public static <T> T value(Object rawValue, TypeReference<T> type) {
return MAPPER.convertValue(rawValue, type);
} public static <T> T value(Object rawValue, JavaType type) {
return MAPPER.convertValue(rawValue, type);
} public static <T> T unwrapJsonP(String raw, Class<T> type) {
return fromJSON(unwrapJsonP(raw), type);
} private static String unwrapJsonP(String raw) {
raw = StringUtils.trim(raw);
raw = StringUtils.removeEnd(raw, ";");
raw = raw.substring(raw.indexOf('(') + 1);
raw = raw.substring(0, raw.lastIndexOf(')'));
raw = StringUtils.trim(raw);
return raw;
} public static <E, T extends Collection<E>> T fromJSON(String json,
Class<? extends Collection> collectionType, Class<E> valueType) {
if (StringUtils.isEmpty(json)) {
json = EMPTY_ARRAY_JSON;
}
try {
return MAPPER.readValue(json,
defaultInstance().constructCollectionType(collectionType, valueType));
} catch (IOException e) {
throw new RuntimeException(e);
}
} /**
* use {@link #fromJson(String)} instead
*/
public static <K, V, T extends Map<K, V>> T fromJSON(String json, Class<? extends Map> mapType,
Class<K> keyType, Class<V> valueType) {
if (StringUtils.isEmpty(json)) {
json = EMPTY_JSON;
}
try {
return MAPPER.readValue(json,
defaultInstance().constructMapType(mapType, keyType, valueType));
} catch (IOException e) {
throw new RuntimeException(e);
}
} public static <T> T fromJSON(InputStream inputStream, Class<T> type) {
try {
return MAPPER.readValue(inputStream, type);
} catch (IOException e) {
throw new RuntimeException(e);
}
} public static <E, T extends Collection<E>> T fromJSON(byte[] bytes,
Class<? extends Collection> collectionType, Class<E> valueType) {
try {
return MAPPER.readValue(bytes,
defaultInstance().constructCollectionType(collectionType, valueType));
} catch (IOException e) {
throw new RuntimeException(e);
}
} public static <E, T extends Collection<E>> T fromJSON(InputStream inputStream,
Class<? extends Collection> collectionType, Class<E> valueType) {
try {
return MAPPER.readValue(inputStream,
defaultInstance().constructCollectionType(collectionType, valueType));
} catch (IOException e) {
throw new RuntimeException(e);
}
} public static Map<String, Object> fromJson(InputStream is) {
return fromJSON(is, Map.class, String.class, Object.class);
} public static Map<String, Object> fromJson(String string) {
return fromJSON(string, Map.class, String.class, Object.class);
} public static Map<String, Object> fromJson(byte[] bytes) {
return fromJSON(bytes, Map.class, String.class, Object.class);
} /**
* use {@link #fromJson(byte[])} instead
*/
public static <K, V, T extends Map<K, V>> T fromJSON(byte[] bytes, Class<? extends Map> mapType,
Class<K> keyType, Class<V> valueType) {
try {
return MAPPER.readValue(bytes,
defaultInstance().constructMapType(mapType, keyType, valueType));
} catch (IOException e) {
throw new RuntimeException(e);
}
} /**
* use {@link #fromJson(InputStream)} instead
*/
public static <K, V, T extends Map<K, V>> T fromJSON(InputStream inputStream,
Class<? extends Map> mapType, Class<K> keyType, Class<V> valueType) {
try {
return MAPPER.readValue(inputStream,
defaultInstance().constructMapType(mapType, keyType, valueType));
} catch (IOException e) {
throw new RuntimeException(e);
}
} public static boolean isJSON(String jsonStr) {
if (StringUtils.isBlank(jsonStr)) {
return false;
}
try (JsonParser parser = new ObjectMapper().getFactory().createParser(jsonStr)) {
while (parser.nextToken() != null) {
// do nothing.
}
return true;
} catch (IOException ioe) {
return false;
}
} public static boolean isBadJSON(String jsonStr) {
return !isJSON(jsonStr);
} }
需要依赖的jackson相关的包有:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-guava -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-guava</artifactId>
<version>2.10.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.hubspot.jackson/jackson-datatype-protobuf -->
<dependency>
<groupId>com.hubspot.jackson</groupId>
<artifactId>jackson-datatype-protobuf</artifactId>
<version>0.9.11-jackson2.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-kotlin -->
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
<version>2.10.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-parameter-names -->
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
<version>2.10.1</version>
</dependency>
json解析工具类的更多相关文章
- 一个强大的json解析工具类
该工具类利用递归原理,能够将任意结构的json字符串进行解析.当然,如果需要解析为对应的实体对象时,就不能用了 package com.wot.cloudsensing.carrotfarm.util ...
- 使用json-lib-*.jar的JSON解析工具类
使用json-lib-2.4-jdk15.jar JSON工具类: import java.util.List; import net.sf.json.JSONArray; import net.sf ...
- 基于json-lib-2.2.2-jdk15.jar的JSON解析工具类大集合
json解析之前的必备工作:导入json解析必须的六个包 资源链接:百度云:链接:https://pan.baidu.com/s/1dAEQQy 密码:1v1z 代码示例: package com.s ...
- Json解析工具Jackson(使用注解)
原文http://blog.csdn.net/nomousewch/article/details/8955796 接上一篇文章Json解析工具Jackson(简单应用),jackson在实际应用中给 ...
- 一个.NET通用JSON解析/构建类的实现(c#)转
转自:http://www.cnblogs.com/xfrog/archive/2010/04/07/1706754.html NET通用JSON解析/构建类的实现(c#) 在.NET Framewo ...
- 自定义Json解析工具
此博客为博主原创文章,转载请标明出处,维权必究:https://www.cnblogs.com/tangZH/p/10689536.html fastjson是很好用的json解析工具,只可惜项目中要 ...
- java后台常用json解析工具问题小结
若排版紊乱可查看我的个人博客原文地址 java后台常用json解析工具问题小结 这里不细究造成这些问题的底层原因,只是单纯的描述我碰到的问题及对应的解决方法 jackson将java对象转json字符 ...
- Java处理JSON的工具类(List、Map和JSON之间的转换)——依赖jsonlib支持Map嵌套
原文链接:http://www.itjhwd.com/java_json/ 代码 package com.itjh.mmp.util; import java.io.BufferedReader; i ...
- Jsoup请求http或https返回json字符串工具类
Jsoup请求http或https返回json字符串工具类 所需要的jar包如下: jsoup-1.8.1.jar 依赖jar包如下: httpclient-4.5.4.jar; httpclient ...
随机推荐
- 【Qt开发】QImage设置为8-bit灰度图
项目中用到大量基础图像处理知识,其中灰度图的生成是很重要的一环. 先补充一些基础知识: -------------------------------------------------------- ...
- python 并发编程 多线程 GIL与多线程
GIL与多线程 有了GIL的存在,同一时刻同一进程中只有一个线程被执行 多进程可以利用多核,但是开销大,而python的多线程开销小,但却无法利用多核优势 1.cpu到底是用来做计算的,还是用来做I/ ...
- [转帖]PostgreSQL pg_dump&psql 数据的备份与恢复
PostgreSQL pg_dump&psql 数据的备份与恢复 https://www.cnblogs.com/chjbbs/p/6480687.html 文章写的挺好 今天试了下 挺不 ...
- C++:string操作函数
要想使用标准C++中string类,必须要包含 #include <string>// 注意是<string>,不是<string.h>,带.h的是C语言中的头文件 ...
- Cookie、Session和LocalStorage
前记 前面我已经写了一篇关于Cookie的文章,但是那时候我其实理解的并不是很深刻,会有些搞不懂的地方,今天我就再写一次,博客也是我的学习笔记 Cookie Cookie是服务器发送到用户浏览器并保存 ...
- 3.学习Dispatcher
3.学习Dispatcher 不管是WinForm应用程序还是WPF应用程序,实际上都是一个进程,一个进程可以包含多个线程,其中有一个是主线程,其余的是子线程. 在WPF或WinForm应用程序中,主 ...
- tp5+layui实现分页
layui和thinkphp5自己在百度上下载 html代码 <!DOCTYPE html> <html> <head> <meta charset=&quo ...
- Vue安装与简单使用
Vue入门 使用Typora打开https://pan.baidu.com/s/1Mf3ZFSthdVUQevqWr777eA 提取码: hg9b vue中文官网教学 安装与使用,我也经常看这个 点击 ...
- 人工智能AI从入门到精通所有视频教程(140G)以及数据资料免费拿
包含了人工智能AI从入门到精通所有视频教程(140G). 资料获取方式,关注公总号RaoRao1994,查看往期精彩-所有文章,即可获取资源下载链接 更多资源获取,请关注公总号RaoRao1994
- centos7进入单用户模式修改root密码
1.开机 按“e”,然后输入init=/bin/sh 2.根据提示按ctrl+x 得如下图: 3.输入mount -o remount,rw / 输入passwd设置新密码.如下图: 4.输 ...