Gson
public class GsonHelper {
private static final String DEFAULT_DATE_TIME_FORMATTER = "yyyy-MM-dd HH:mm:ss";
private static final String DEFAULT_DATE_FORMATTER = "yyyy-MM-dd";
private static final String DEFAULT_TIME_FORMATTER = "HH:mm:ss";
private static final Gson GSON;
private static final JsonParser JSON_PARSER = new JsonParser();
private static final Gson PRETTY_GSON;
/*
* 增加java8 时间处理类序列化反序列化
* @since 1.2.5
*/
static {
GSON = new GsonBuilder()
.serializeNulls()
.registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (localDateTime, typeOfSrc, context) -> {
if (Objects.isNull(localDateTime)) {
return new JsonPrimitive("");
}
return new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMATTER)));
})
.registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (json1, typeOfT, context) -> {
String string = json1.getAsJsonPrimitive().getAsString();
if (Strings.isNullOrEmpty(string)) {
return null;
}
return LocalDateTime.parse(string, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMATTER));
})
.registerTypeAdapter(LocalDate.class, (JsonSerializer<LocalDate>) (localDate, type, jsonSerializationContext) -> {
if (Objects.isNull(localDate)) {
return new JsonPrimitive("");
}
return new JsonPrimitive(localDate.format(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMATTER)));
})
.registerTypeAdapter(LocalDate.class, (JsonDeserializer<LocalDate>) (json, typeOfT, context) -> {
String string = json.getAsJsonPrimitive().getAsString();
if (Strings.isNullOrEmpty(string)) {
return null;
}
return LocalDate.parse(string, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMATTER));
})
.registerTypeAdapter(LocalTime.class, (JsonSerializer<LocalTime>) (localTime, type, jsonSerializationContext) -> {
if (Objects.isNull(localTime)) {
return new JsonPrimitive("");
}
return new JsonPrimitive(localTime.format(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMATTER)));
})
.registerTypeAdapter(LocalTime.class, (JsonDeserializer<LocalTime>) (json, typeOfT, context) -> {
String string = json.getAsJsonPrimitive().getAsString();
if (Strings.isNullOrEmpty(string)) {
return null;
}
return LocalTime.parse(string, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMATTER));
})
.create();
PRETTY_GSON = new GsonBuilder()
.serializeNulls()
.registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (localDateTime, typeOfSrc, context) -> {
if (Objects.isNull(localDateTime)) {
return new JsonPrimitive("");
}
return new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMATTER)));
})
.registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (json1, typeOfT, context) -> {
String string = json1.getAsJsonPrimitive().getAsString();
if (Strings.isNullOrEmpty(string)) {
return null;
}
return LocalDateTime.parse(string, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMATTER));
})
.registerTypeAdapter(LocalDate.class, (JsonSerializer<LocalDate>) (localDate, type, jsonSerializationContext) -> {
if (Objects.isNull(localDate)) {
return new JsonPrimitive("");
}
return new JsonPrimitive(localDate.format(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMATTER)));
})
.registerTypeAdapter(LocalDate.class, (JsonDeserializer<LocalDate>) (json, typeOfT, context) -> {
String string = json.getAsJsonPrimitive().getAsString();
if (Strings.isNullOrEmpty(string)) {
return null;
}
return LocalDate.parse(string, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMATTER));
})
.registerTypeAdapter(LocalTime.class, (JsonSerializer<LocalTime>) (localTime, type, jsonSerializationContext) -> {
if (Objects.isNull(localTime)) {
return new JsonPrimitive("");
}
return new JsonPrimitive(localTime.format(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMATTER)));
})
.registerTypeAdapter(LocalTime.class, (JsonDeserializer<LocalTime>) (json, typeOfT, context) -> {
String string = json.getAsJsonPrimitive().getAsString();
if (Strings.isNullOrEmpty(string)) {
return null;
}
return LocalTime.parse(string, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMATTER));
})
.setPrettyPrinting()
.create();
}
/**
* Json美化输出工具
*
* @param json json string
* @return beauty json string
*/
public static String toPrettyFormat(String json) {
JsonElement jsonElement = JSON_PARSER.parse(json);
return PRETTY_GSON.toJson(jsonElement);
}
/**
* 美化json
*
* @param object obj
* @return beauty json string
*/
public static String toPrettyFormat(Object object) {
return toPrettyFormat(object2Json(object));
}
/**
* Json转换成对象
*
* @param json json string
* @param <T> 对象类型
* @return T
*/
public static <T> T json2Object(String json, Class<T> t) {
return GSON.fromJson(json, t);
}
/**
* Json转换成对象
* 该方式适用于泛型内包含泛型,如想转换的返回值为:User<String>
* 使用方式
* <code>
* Type type = new TypeToken<User<String>>(){}.getType();
* User<String> user = JsonHelper.json2Object(json,type);
* </code>
*
* @param json json
* @param type type
* @param <T> T
* @return T
*/
public static <T> T json2Object(String json, Type type) {
return GSON.fromJson(json, type);
}
/**
* 对象转换成Json字符串
* json分为对象和数组两种类型,需要分别处理
*
* @param object obj
* @return json string
*/
public static String object2Json(Object object) {
return GSON.toJson(object);
}
/**
* json转换成JsonElement
*
* @param json jsonStr
* @return {@link JsonElement}
*/
public static JsonElement json2JsonElement(String json) {
return JSON_PARSER.parse(json);
}
}
Jackson
@Slf4j
public class JacksonHelper {
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final String DEFAULT_DATE_TIME_FORMATTER = "yyyy-MM-dd HH:mm:ss";
private static final String DEFAULT_DATE_FORMATTER = "yyyy-MM-dd";
private static final String DEFAULT_TIME_FORMATTER = "HH:mm:ss";
static {
@Slf4j
public class JacksonHelper {
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final String DEFAULT_DATE_TIME_FORMATTER = "yyyy-MM-dd HH:mm:ss";
private static final String DEFAULT_DATE_FORMATTER = "yyyy-MM-dd";
private static final String DEFAULT_TIME_FORMATTER = "HH:mm:ss";
static {
objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// objectMapper.registerModule(new JavaTimeModule());
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object value, JsonGenerator jg,
SerializerProvider sp) throws IOException,
JsonProcessingException {
jg.writeString("");
}
});
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
@Override
public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
String value = jsonParser.getValueAsString();
if (Strings.isNullOrEmpty(value)) {
return null;
}
return LocalDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMATTER));
}
});
javaTimeModule.addSerializer(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
@Override
public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (Objects.isNull(localDateTime)) {
jsonGenerator.writeString("");
}
jsonGenerator.writeString(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMATTER).format(localDateTime));
}
});
javaTimeModule.addDeserializer(LocalDate.class, new JsonDeserializer<LocalDate>() {
@Override
public LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
if(Strings.isNullOrEmpty(jsonParser.getValueAsString())){
return null;
}
return LocalDate.parse(jsonParser.getValueAsString(), DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMATTER));
}
});
javaTimeModule.addSerializer(LocalDate.class, new JsonSerializer<LocalDate>() {
@Override
public void serialize(LocalDate localDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (Objects.isNull(localDate)) {
jsonGenerator.writeString("");
}else {
jsonGenerator.writeString(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMATTER).format(localDate));
}
}
});
javaTimeModule.addDeserializer(LocalTime.class, new JsonDeserializer<LocalTime>() {
@Override
public LocalTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
if(Strings.isNullOrEmpty(jsonParser.getValueAsString())){
return null;
}
return LocalTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMATTER));
}
});
javaTimeModule.addSerializer(LocalTime.class, new JsonSerializer<LocalTime>() {
@Override
public void serialize(LocalTime localTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if(Objects.isNull(localTime)){
jsonGenerator.writeString("");
}
jsonGenerator.writeString(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMATTER).format(localTime));
}
});
objectMapper.registerModules(javaTimeModule);
}
public static String obj2Json(Object obj) throws IOException {
return objectMapper.writeValueAsString(obj);
}
public static <T> T json2Obj(String json, Class<T> clazz) throws IOException {
return objectMapper.readValue(json, clazz);
}
/**
* 可以把Json字符串转换成List
*/
public static <T> T parseObject(String json, TypeReference<T> typeReference) {
try {
return (T) objectMapper.readValue(json, typeReference);
} catch (JsonParseException e) {
log.error("parseObject(String, TypeReference<T>) JsonParseException", e);
} catch (JsonMappingException e) {
log.error("parseObject(String, TypeReference<T>) JsonMappingException", e);
} catch (IOException e) {
log.error("parseObject(String, TypeReference<T>)", e);
}
return null;
}
public static JsonNode readRootNode(String json) {
return readAnyNode(json, null);
}
/**
* 根据json key 获取任意层级的jsonNode
*/
public static JsonNode readAnyNode(String json, String fieldName) {
try {
JsonNode rootNode = objectMapper.readTree(json);
if (Strings.isNullOrEmpty(fieldName)) {
return rootNode;
}
return rootNode.findValue(fieldName);
} catch (IOException e) {
log.error("readNode(String json,String fieldName)", e);
}
return null;
}
//创建jsonNode
public static ObjectNode createObjectNode() {
return objectMapper.createObjectNode();
}
/**
* 格式化输出json
*/
public static <T> String console(T t) {
String json = "";
try {
json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(t);
} catch (JsonGenerationException e) {
log.error("console(T t) JsonGenerationException", e);
} catch (JsonMappingException e) {
log.error("console(T t) JsonMappingException", e);
} catch (IOException e) {
log.error("console(T t)", e);
}
return json;
}
}
}
public static String obj2Json(Object obj) throws IOException {
return objectMapper.writeValueAsString(obj);
}
public static <T> T json2Obj(String json, Class<T> clazz) throws IOException {
return objectMapper.readValue(json, clazz);
}
/**
* 可以把Json字符串转换成List
*/
public static <T> T parseObject(String json, TypeReference<T> typeReference) {
try {
return (T) objectMapper.readValue(json, typeReference);
} catch (JsonParseException e) {
log.error("parseObject(String, TypeReference<T>) JsonParseException", e);
} catch (JsonMappingException e) {
log.error("parseObject(String, TypeReference<T>) JsonMappingException", e);
} catch (IOException e) {
log.error("parseObject(String, TypeReference<T>)", e);
}
return null;
}
public static JsonNode readRootNode(String json) {
return readAnyNode(json, null);
}
/**
* 根据json key 获取任意层级的jsonNode
*/
public static JsonNode readAnyNode(String json, String fieldName) {
try {
JsonNode rootNode = objectMapper.readTree(json);
if (StringUtils.isBlank(fieldName)) {
return rootNode;
}
return rootNode.findValue(fieldName);
} catch (IOException e) {
log.error("readNode(String json,String fieldName)", e);
}
return null;
}
//创建jsonNode
public static ObjectNode createObjectNode() {
return objectMapper.createObjectNode();
}
/**
* 格式化输出json
*/
public static <T> String console(T t) {
String json = "";
try {
json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(t);
} catch (JsonGenerationException e) {
log.error("console(T t) JsonGenerationException", e);
} catch (JsonMappingException e) {
log.error("console(T t) JsonMappingException", e);
} catch (IOException e) {
log.error("console(T t)", e);
}
return json;
}
}