Skip to content

Commit ffad658

Browse files
author
fxbin
committed
refactor: ♻️ 增加json操作相关方法
1 parent 5e3328f commit ffad658

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

bubble-core/src/main/java/cn/fxbin/bubble/core/util/JsonUtils.java

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
11
package cn.fxbin.bubble.core.util;
22

3+
import cn.fxbin.bubble.core.dataobject.GlobalErrorCode;
4+
import cn.fxbin.bubble.core.exception.ServiceException;
35
import cn.fxbin.bubble.core.exception.UtilException;
46
import cn.fxbin.bubble.core.module.JacksonHolder;
57
import cn.hutool.json.JSONUtil;
68
import com.fasterxml.jackson.core.JsonProcessingException;
9+
import com.fasterxml.jackson.core.type.TypeReference;
10+
import com.google.common.collect.Lists;
711
import lombok.experimental.UtilityClass;
12+
import org.springframework.lang.NonNull;
813

914
import java.io.IOException;
15+
import java.util.List;
16+
import java.util.Map;
17+
import java.util.stream.Collectors;
1018

1119
/**
1220
* JsonUtils
@@ -54,6 +62,41 @@ public byte[] toJsonByte(Object value) {
5462
}
5563
}
5664

65+
/**
66+
* 提取
67+
*
68+
* @param jsonStr json str
69+
* @param fieldName 字段名
70+
* @param delim delim
71+
* @return {@link String}
72+
*/
73+
public String extract(String jsonStr, @NonNull String fieldName, String delim) {
74+
List<String> list = JsonUtils.extract(jsonStr, fieldName);
75+
return StringUtils.join(list, delim);
76+
}
77+
78+
/**
79+
* 提取字段数据
80+
*
81+
* @param jsonStr json str
82+
* @param fieldName 字段名
83+
* @return {@link List}<{@link String}>
84+
*/
85+
public List<String> extract(String jsonStr, @NonNull String fieldName) {
86+
87+
if (StringUtils.isNotBlank(jsonStr) && JsonUtils.isJsonString(jsonStr)) {
88+
List<Map<String, Object>> mapList;
89+
try {
90+
mapList = JsonUtils.parse(jsonStr, new TypeReference<>() {
91+
});
92+
} catch (Exception e) {
93+
throw new ServiceException(GlobalErrorCode.INTERNAL_SERVER_ERROR);
94+
}
95+
96+
return mapList.stream().map(m -> StringUtils.utf8Str(m.get(fieldName))).collect(Collectors.toList());
97+
}
98+
return Lists.newArrayList();
99+
}
57100

58101
/**
59102
* isJsonString 是否为json格式字符串
@@ -105,4 +148,19 @@ public <T> T parse(String jsonString, Class<T> requiredType) {
105148
}
106149
}
107150

151+
/**
152+
* parse
153+
*
154+
* @param content json content
155+
* @param valueTypeRef TypeReference
156+
* @return {@link T}
157+
*/
158+
public <T> T parse(String content, TypeReference<T> valueTypeRef) {
159+
try {
160+
return JacksonHolder.INSTANCE.readValue(content, valueTypeRef);
161+
} catch (IOException e) {
162+
throw new UtilException(e);
163+
}
164+
}
165+
108166
}

0 commit comments

Comments
 (0)