JsonUtils.java
1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.xly.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import java.io.IOException;
import java.util.List;
public class JsonUtils {
private static final ObjectMapper objectMapper = new ObjectMapper();
// JSON字符串转Java对象
public static <T> T toObject(String json, Class<T> clazz) {
try {
return objectMapper.readValue(json, clazz);
} catch (IOException e) {
throw new RuntimeException("JSON解析失败", e);
}
}
// JSON字符串转List
public static <T> List<T> toList(String json, Class<T> clazz) {
try {
CollectionType listType = TypeFactory.defaultInstance()
.constructCollectionType(List.class, clazz);
return objectMapper.readValue(json, listType);
} catch (IOException e) {
throw new RuntimeException("JSON解析失败", e);
}
}
// 对象转JSON字符串
public static String toJson(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (IOException e) {
throw new RuntimeException("JSON生成失败", e);
}
}
}