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 ...
随机推荐
- BZOJ3129方程(SDOI2013)
https://blog.csdn.net/Maxwei_wzj/article/details/80152116 对变量有上界限制及下界限制.对于下界,可以从总数中减去即可,对于上界,容斥定理.
- 【VS开发】Cameralink接口
目录 1 Camera Link接口的三种配置 ▪ Base Camera Link ▪ Medium Camera Link ▪ Full Camera Link 2 Camera Link三种接口 ...
- python 并发编程 同步调用和异步调用 回调函数
提交任务的两张方式: 1.同步调用 2.异步调用 同步调用:提交完任务后,就在原地等待任务执行完后,拿到结果,再执行下一行代码 同步调用,导致程序串行执行 from concurrent.future ...
- Mac OS X 11中的/usr/bin 的“Operation not permitted”
更新了 Mac OS X 11后发现,MacVim 不再能够通过Terminal用命令打开了. mvim hello.txt 于是尝试将 mvim 重新复制到/usr/bin/中去 sudo cp - ...
- C语言博客作业05
这个作业属于哪个课程 C语言程序设计II 这个作业要求在那里 https://edu.cnblogs.com/campus/zswxy/CST2019-3/homework/9827 我在这个课程的目 ...
- Almost Sorted Array(o(nlgn)求解LIS)
Almost Sorted Array Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Ot ...
- 【7.10校内test】T2不等数列
[题目链接luogu] 此题在luogu上模数是2015,考试题的模数是2012. 然后这道题听说好多人是打表找规律的(就像7.9T2一样)(手动滑稽_gc) 另外手动 sy,每次测试都无意之间bib ...
- python3—廖雪峰之练习(一)
变量练习 小明的成绩从去年的72分提升到今年的85分,请计算小明成绩提升的百分点.并用 字符串格式化显示出'xx.x%',只保留小数点后一位: s1 = 72 s2 = 85 r = (85-72)/ ...
- Vue配置bs环境
安装插件 jQuery >: cnpm install jquery vue/cli 3 配置jQuery:在vue.config.js中配置(没有,手动项目根目录下新建) const webp ...
- eval解惑
let a = 1, b = 2, c = 3; let arr = [a, b, c]; function test(p1, p2, p3) { console.log(`${p1} ~ ${p2} ...