java json转换工具类

在java项目中,通常会用到json类型的转换,常常需要对 json字符串和对象进行相互转换。

在制作自定义的json转换类之前,先引入以下依赖

 
 
<!--json相关工具-->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-guava</artifactId> <!--google-->
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
 
 

自定义json工具类的实现:

 
 
package com.me.util;

import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.TypeReference;
/**
* json转换
*/
@Slf4j
public class JsonMapper {

private static ObjectMapper objectMapper = new ObjectMapper();
static {
// config
objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
}

/**
* 对象转为json字符串
* @param src
* @param <T>
* @return
*/
public static <T> String obj2String(T src){
if(src == null){
return null;
}
try{
return src instanceof String ? (String) src : objectMapper.writeValueAsString(src);
} catch (Exception e) {
log.warn("parse object to String exception",e);
return null;
}
}

/**
* json字符串转为对象
* @param src
* @param typeReference
* @param <T>
* @return
*/
public static <T> T string2Obj(String src, TypeReference<T> typeReference) {
if (src == null || typeReference == null) {
return null;
}
try {
return (T) (typeReference.getType().equals(String.class) ? src : objectMapper.readValue(src, typeReference));
} catch (Exception e) {
log.warn("parse String to Object exception, String:{}, TypeReference<T>:{}, error:{}", src, typeReference.getType(), e);
return null;
}
}

}

使用:

JSON串转为list类型

对象类型转为JSON串

 

转载于:https://www.cnblogs.com/devise/p/9974659.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值