一、maven依赖引入jackson
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.5</version>
</dependency>
jackson-databind依赖见下:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
二、JsonUtil工具类
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil {
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* Json encode
*
* @param object object
* @return String
*/
public static String encode(Object object) {
try {
return OBJECT_MAPPER.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new RuntimeException("Json encode failed!", e);
}
}
/**
* Json decode
*
* @param json json
* @param typeReference typeReference
* @param <T> T
* @return T
*/
public static <T> T decode(String json, TypeReference<T> typeReference) {
try {
return OBJECT_MAPPER.readValue(json, typeReference);
} catch (Exception e) {
throw new RuntimeException("Json decode failed!", e);
}
}
/**
* Json decode
*
* @param json json
* @param targetClass targetClass
* @param <T> T
* @return T
*/
public static <T> T decode(String json, Class<T> targetClass) {
try {
return OBJECT_MAPPER.readValue(json, targetClass);
} catch (Exception e) {
throw new RuntimeException("Json decode failed!", e);
}
}
}
三、使用示例
定义一个User对象
@AllArgsConstructor
@NoArgsConstructor
@Data
public static class User {
private String name;
private Integer age;
}
- encode() 单个对象
String str = JsonUtil.encode(new User("张三", 10));
// {"name":"张三","age":10}
System.out.println(str);
- encode() 对象集合
List<User> userList = Lists.newArrayList();
userList.add(new User("张三", 10));
userList.add(new User("李四", 12));
String str = JsonUtil.encode(userList);
// [{"name":"张三","age":10},{"name":"李四","age":12}]
System.out.println(str);
- decode() 单个对象
String json = "{\"name\":\"stelin\",\"age\":18}";
User user = JsonUtil.decode(json, User.class);
// JsonUtil.User(name=stelin, age=18)
System.out.println(user);
- decode() 对象集合
String str = "[{\"name\":\"张三\",\"age\":10},{\"name\":\"李四\",\"age\":12}]";
List<User> userList = JsonUtil.decode(str, new TypeReference<List<User>>() {
});
// [JsonUtil.User(name=张三, age=10), JsonUtil.User(name=李四, age=12)]
System.out.println(userList);
- decode() 字符串集合
String str = "[1, 2, 3]";
List<String> list = JsonUtil.decode(str, new TypeReference<List<String>>() {
});
// [1, 2, 3]
System.out.println(list);
很多jar包都会有类TypeReference,别错误地引用了,注意这里的TypeReference是com.fasterxml.jackson.core.type.TypeReference。