对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解析工具类的更多相关文章

  1. 一个强大的json解析工具类

    该工具类利用递归原理,能够将任意结构的json字符串进行解析.当然,如果需要解析为对应的实体对象时,就不能用了 package com.wot.cloudsensing.carrotfarm.util ...

  2. 使用json-lib-*.jar的JSON解析工具类

    使用json-lib-2.4-jdk15.jar JSON工具类: import java.util.List; import net.sf.json.JSONArray; import net.sf ...

  3. 基于json-lib-2.2.2-jdk15.jar的JSON解析工具类大集合

    json解析之前的必备工作:导入json解析必须的六个包 资源链接:百度云:链接:https://pan.baidu.com/s/1dAEQQy 密码:1v1z 代码示例: package com.s ...

  4. Json解析工具Jackson(使用注解)

    原文http://blog.csdn.net/nomousewch/article/details/8955796 接上一篇文章Json解析工具Jackson(简单应用),jackson在实际应用中给 ...

  5. 一个.NET通用JSON解析/构建类的实现(c#)转

    转自:http://www.cnblogs.com/xfrog/archive/2010/04/07/1706754.html NET通用JSON解析/构建类的实现(c#) 在.NET Framewo ...

  6. 自定义Json解析工具

    此博客为博主原创文章,转载请标明出处,维权必究:https://www.cnblogs.com/tangZH/p/10689536.html fastjson是很好用的json解析工具,只可惜项目中要 ...

  7. java后台常用json解析工具问题小结

    若排版紊乱可查看我的个人博客原文地址 java后台常用json解析工具问题小结 这里不细究造成这些问题的底层原因,只是单纯的描述我碰到的问题及对应的解决方法 jackson将java对象转json字符 ...

  8. Java处理JSON的工具类(List、Map和JSON之间的转换)——依赖jsonlib支持Map嵌套

    原文链接:http://www.itjhwd.com/java_json/ 代码 package com.itjh.mmp.util; import java.io.BufferedReader; i ...

  9. Jsoup请求http或https返回json字符串工具类

    Jsoup请求http或https返回json字符串工具类 所需要的jar包如下: jsoup-1.8.1.jar 依赖jar包如下: httpclient-4.5.4.jar; httpclient ...

随机推荐

  1. PEP8-python编码规范(上)

    包含主要 Python 发行版中的标准库的 Python 代码的编码约定. 1.代码缩进 (1)每个缩进需要使用 4 个空格.一般使用一个Tab键. Python 3 不允许混合使用制表符和空格来缩进 ...

  2. vue ----》实现打印功能

    1.安装打印相关依赖 cnpm install vue-print-nb --save 2.安装后,在main.js文件中引入 import Print from 'vue-print-nb' Vue ...

  3. sqlplus语句示例

    我们通常所说的DML.DDL.DCL语句都是sql*plus语句,它们执行完后,都可以保存在一个被称为sql buffer的内存区域中,并且只能保存一条最近执行的sql语句,我们可以对保存在sql b ...

  4. MongoDB和Redis的区别

    1).内存管理机制 a.Redis的数据全部存储在内存当中,会定期写入到磁盘当中,当内存不够用时, 可以选择指定的LRU(最近最少使用算法)的算法删除数据: b.MongoDB数据存在内存,有Linu ...

  5. Logistic回归应用-预测马的死亡率

    Logistic回归应用-预测马的死亡率 本文所有代码均来自<机器学习实战>,数据也是 本例中的数据有以下几个特征: 部分指标比较主观.难以很好的定量测量,例如马的疼痛级别 数据集中有30 ...

  6. 运维ipvsadm配置负载均衡

    一.负载均衡LVS基本介绍 LB集群的架构和原理很简单,就是当用户的请求过来时,会直接分发到Director Server上,然后它把用户的请求根据设置好的调度算法,智能均衡地分发到后端真正服务器(r ...

  7. fullpage实现(-)

    在线demo还没弄好,地址先给出来

  8. nginx的代理服务

    nginx的代理服务 正向代理和反向代理 正向代理服务器就是用来让局域网的客户端接入外网访问外网资源,反向代理就是让外网的客户端接入局域网中的站点以访问点中的资源 正向代理 我是一个用户,我访问不了某 ...

  9. 【转】linux下 如何切换到root用户

    转自:https://www.cnblogs.com/xinjie10001/p/6295020.html 默认安装完成之后并不知道root用户的密码,那么如何应用root权限呢? (1)sudo 命 ...

  10. Android 静态代码分析工具

    简评: 作者在文中提到的三个静态代码分析工具不是互相替代的关系,各有各的侧重点,如果有需要完全可以同时使用. 静态代码分析是指无需运行被测代码,仅通过分析或检查源程序的语法.结构.过程.接口等来检查程 ...