Skip to content

Commit

Permalink
refactor: ♻️ 优化JsonUtils 实现
Browse files Browse the repository at this point in the history
  • Loading branch information
fxbin committed Aug 30, 2023
1 parent 7b868bb commit f4d39db
Showing 1 changed file with 12 additions and 18 deletions.
30 changes: 12 additions & 18 deletions bubble-core/src/main/java/cn/fxbin/bubble/core/util/JsonUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import cn.fxbin.bubble.core.exception.UtilException;
import cn.fxbin.bubble.core.module.JacksonHolder;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.experimental.UtilityClass;

import java.io.IOException;
Expand All @@ -16,7 +16,7 @@
* @since 2020/3/20 17:28
*/
@UtilityClass
public class JsonUtils {
public class JsonUtils extends JSONUtil {


/**
Expand All @@ -28,7 +28,13 @@ public class JsonUtils {
*/
public String toJson(Object object) {
try {
return getInstance().writeValueAsString(object);
if (ObjectUtils.isEmpty(object)) {
return null;
}
if (object instanceof CharSequence) {
return StringUtils.utf8Str(object);
}
return JacksonHolder.INSTANCE.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new UtilException(e);
}
Expand All @@ -44,7 +50,7 @@ public String toJson(Object object) {
*/
public boolean isJsonString(String jsonString) {
try {
getInstance().readTree(jsonString);
JacksonHolder.INSTANCE.readTree(jsonString);
return true;
} catch (IOException e) {
return false;
Expand All @@ -61,7 +67,7 @@ public boolean isJsonString(String jsonString) {
*/
public boolean isJsonSerialize(Object object) {
try {
getInstance().writeValueAsBytes(object);
JacksonHolder.INSTANCE.writeValueAsBytes(object);
return true;
} catch (JsonProcessingException e) {
return false;
Expand All @@ -79,22 +85,10 @@ public boolean isJsonSerialize(Object object) {
*/
public <T> T parse(String jsonString, Class<T> requiredType) {
try {
return getInstance().readValue(jsonString, requiredType);
return JacksonHolder.INSTANCE.readValue(jsonString, requiredType);
} catch (IOException e) {
throw new UtilException(e);
}
}


/**
* getInstance 获取jackson实例
*
* @since 2020/3/20 17:30
* @return com.fasterxml.jackson.databind.ObjectMapper
*/
private ObjectMapper getInstance() {
return JacksonHolder.INSTANCE;
}


}

0 comments on commit f4d39db

Please sign in to comment.