|
1 | 1 | package cn.fxbin.bubble.core.util;
|
2 | 2 |
|
| 3 | +import cn.fxbin.bubble.core.dataobject.GlobalErrorCode; |
| 4 | +import cn.fxbin.bubble.core.exception.ServiceException; |
3 | 5 | import cn.fxbin.bubble.core.exception.UtilException;
|
4 | 6 | import cn.fxbin.bubble.core.module.JacksonHolder;
|
5 | 7 | import cn.hutool.json.JSONUtil;
|
6 | 8 | import com.fasterxml.jackson.core.JsonProcessingException;
|
| 9 | +import com.fasterxml.jackson.core.type.TypeReference; |
| 10 | +import com.google.common.collect.Lists; |
7 | 11 | import lombok.experimental.UtilityClass;
|
| 12 | +import org.springframework.lang.NonNull; |
8 | 13 |
|
9 | 14 | import java.io.IOException;
|
| 15 | +import java.util.List; |
| 16 | +import java.util.Map; |
| 17 | +import java.util.stream.Collectors; |
10 | 18 |
|
11 | 19 | /**
|
12 | 20 | * JsonUtils
|
@@ -54,6 +62,41 @@ public byte[] toJsonByte(Object value) {
|
54 | 62 | }
|
55 | 63 | }
|
56 | 64 |
|
| 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 | + } |
57 | 100 |
|
58 | 101 | /**
|
59 | 102 | * isJsonString 是否为json格式字符串
|
@@ -105,4 +148,19 @@ public <T> T parse(String jsonString, Class<T> requiredType) {
|
105 | 148 | }
|
106 | 149 | }
|
107 | 150 |
|
| 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 | + |
108 | 166 | }
|
0 commit comments