测试用户
2023-04-13 43393f2bb11cbf9e6af40077bbc5284660e8a754
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.common.core.utils;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
 
import java.io.IOException;
import java.util.Collection;
import java.util.List;
 
/**
 * Json转换工具类
 */
@Slf4j
public class JsonUtils {
 
    public static final ObjectMapper objectMapper = new ObjectMapper();
 
    /**
     * 字符串转对象
     *
     * @param jsonStr json字符串
     * @param clazz   转换类型
     * @param <T>
     * @return
     */
    public static <T> T string2Object(String jsonStr, Class<T> clazz) throws IOException {
        return objectMapper.readValue(jsonStr, clazz);
    }
 
    /**
     * 字符串转列表
     *
     * @param jsonStr json字符串
     * @param clazz   类型
     * @param <T>
     * @return
     * @throws JsonProcessingException
     */
    public static <T> Collection<T> string2List(String jsonStr, Class<T> clazz) throws IOException {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(Collection.class, clazz);
        return (Collection<T>) objectMapper.readValue(jsonStr, javaType);
    }
 
    /**
     * 对象转字符串
     *
     * @param object 对象
     * @return
     * @throws JsonProcessingException
     */
    public static String object2String(Object object) {
        if (object == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.warn("对象转字符串", e);
        }
        return null;
    }
 
 
    public static String list2String(List object){
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
 
}