You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.8 KiB
66 lines
1.8 KiB
package com.gk.study.utils;
|
|
|
|
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
|
|
import com.fasterxml.jackson.core.type.TypeReference;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import org.springframework.util.StringUtils;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
public class JsonUtils {
|
|
private static final ObjectMapper objectMapper = new ObjectMapper();
|
|
|
|
public static String toJsonString(Object object) {
|
|
try {
|
|
return objectMapper.writeValueAsString(object);
|
|
} catch (Exception e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
public static <T> T parseObject(String text, Class<T> clazz) {
|
|
if (StringUtils.isEmpty(text)) {
|
|
return null;
|
|
}
|
|
try {
|
|
return objectMapper.readValue(text, clazz);
|
|
} catch (Exception e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
|
|
if (bytes == null || bytes.length <= 0) {
|
|
return null;
|
|
}
|
|
try {
|
|
return objectMapper.readValue(bytes, clazz);
|
|
} catch (Exception e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
public static <T> T parseObject(String text, TypeReference<T> typeReference) {
|
|
try {
|
|
return objectMapper.readValue(text, typeReference);
|
|
} catch (Exception e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
public static <T> List<T> parseArray(String text, Class<T> clazz) {
|
|
if (StringUtils.isEmpty(text)) {
|
|
return new ArrayList<>();
|
|
}
|
|
try {
|
|
return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
|
|
} catch (Exception e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
|