- Jackson 工具类
- 对象转字符串
- 字符串转对象
- 字符串转未知对象 (
TypeReference
实现) - 字符串转集合类 ```java
/**
jackson 序列化工具类 */ @Slf4j public class JacksonUtil { private JacksonUtil() { }
private static final ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
// 对象的所有属性都保留
objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
// 取消默认转换为timestamp形式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
// 忽略空 bean 转 json 的错误
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// 所有的日期格式都统一为 yyyy-MM-dd HH:mm:ss
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 忽略在 json 字符串中存在,对应 bean 不存在字段的情况,避免错误
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
/**
对象转字符串
*- @param obj 对象
- @param
对象类型 @return {@link String} 序列化后的字符串 */ public static
String obj2String(T obj) { if (Objects.isNull(obj)) { return null;
} try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse object to String error: {}", e.getLocalizedMessage(), e);
return null;
} }
/**
对象转字符串, 友好展示
*- @param obj 对象
- @param
对象类型 @return {@link String} 序列化后的字符串 */ public static
String obj2StringPretty(T obj) { if (Objects.isNull(obj)) { return null;
} try {
return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse object to String error: {}", e.getLocalizedMessage(), e);
return null;
} }
/**
字符串转对象
*- @param str json 字符串
- @param tClass 要转换的对象 class 对象
- @param
要转换的对象类型 @return 转换后的对象 */ public static
T string2Obj(String str, Class tClass) { if (Objects.isNull(str) || “”.equals(str) || Objects.isNull(tClass)) { return null;
} try {
return tClass == String.class ? (T) str : objectMapper.readValue(str, tClass);
} catch (Exception e) {
log.warn("Parse String to obj error: {}", e.getLocalizedMessage(), e);
return null;
} }
/**
根据 TypeReference {@link TypeReference} 将字符串转为对象
*- @param str json字符串
- @param typeReference 引用类型
- @param
对象类型 @return 转换后的对象 */ public static
T string2Obj(String str, TypeReference typeReference) { if (Objects.isNull(str) || “”.equals(str) || Objects.isNull(typeReference)) { return null;
} try {
return typeReference.getType().equals(String.class) ? (T) str : objectMapper.readValue(str, typeReference);
} catch (Exception e) {
log.warn("Parse String to obj error: {}", e.getLocalizedMessage(), e);
return null;
} }
/**
将字符串转换为集合类对象
*- @param str json 字符串
- @param collectionClass 集合类 class
- @param itemClasses 元素 class
- @param
对象类型 @return 转换后的对象 */ public static
T string2Obj(String str, Class<?> collectionClass, Class<?>… itemClasses) { JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, itemClasses); try { return objectMapper.readValue(str, javaType);
} catch (Exception e) {
log.warn("Parse String to obj error: {}", e.getLocalizedMessage(), e);
return null;
} }
/**
测试类 */ @Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString private static class User1 { private Integer id;
private String name;
@JsonDeserialize(using = LocalDateTimeDeserializer.class) @JsonSerialize(using = LocalDateTimeSerializer.class) private LocalDateTime localDateTime;
private Date date;
}
/**
* 测试
*/
public static void main(String[] args) {
User1 user1 = new User1();
user1.setId(100);
user1.setLocalDateTime(LocalDateTime.now());
user1.setDate(new Date());
// 对象转字符串
String str = JacksonUtil.obj2String(user1);
System.out.println(str);
// 对象转字符串 友好展示
str = JacksonUtil.obj2StringPretty(user1);
System.out.println(str);
// 字符串转对象
System.out.println(JacksonUtil.string2Obj(str, User1.class));
List<User1> user1List = new ArrayList<>();
user1List.add(new User1(1, "a", LocalDateTime.now(), new Date()));
user1List.add(new User1(2, "b", LocalDateTime.now(), new Date()));
user1List.add(new User1(3, "c", LocalDateTime.now(), new Date()));
System.out.println("=============================================================");
str = JacksonUtil.obj2String(user1List);
// 字符串转未知类型
System.out.println(JacksonUtil.string2Obj(str, new TypeReference<List<User1>>() {
}));
// 字符串转集合类型
List<User1> user1List2 = JacksonUtil.string2Obj(str, List.class, User1.class);
System.out.println(user1List2);
}
}
```