JsonPathUtils.java
2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.diligrp.tax.central.utils;
import com.diligrp.tax.central.exception.TaxAgentServiceException;
import com.diligrp.tax.central.type.TaxSystemType;
import com.fasterxml.jackson.core.type.TypeReference;
import com.jayway.jsonpath.JsonPath;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* @Author: zhangmeiyang
* @CreateTime: 2025-11-11 11:21
* @Version: todo
*/
public class JsonPathUtils {
public static Object parse(String httpResult, String dataPath) {
Optional.ofNullable(httpResult).orElseThrow(() -> new TaxAgentServiceException(TaxSystemType.REMOTE_SERVICE_CALLS_ARE_EXCEPTIONAL));
Optional.ofNullable(dataPath).orElseThrow(() -> new TaxAgentServiceException(TaxSystemType.PARAMETER_IS_NOT_PARSED_CORRECTLY));
return JsonPath.read(httpResult, dataPath);
}
public static String parseString(String httpResult, String dataPath) {
Optional.ofNullable(httpResult).orElseThrow(() -> new TaxAgentServiceException(TaxSystemType.REMOTE_SERVICE_CALLS_ARE_EXCEPTIONAL));
Optional.ofNullable(dataPath).orElseThrow(() -> new TaxAgentServiceException(TaxSystemType.PARAMETER_IS_NOT_PARSED_CORRECTLY));
var res = JsonPath.read(httpResult, dataPath);
return Optional.ofNullable(res).map(Object::toString).orElse("");
}
/**
* 解析到map
*
* @param httpResult
* @param dataPathMap 数据路径图
* @return {@link Map }<{@link String }, {@link Object }>
*/
public static Map<String, Object> parseToMap(String httpResult, Map<String, String> dataPathMap) {
Map<String, Object> res = new HashMap<>();
Optional.ofNullable(httpResult).orElseThrow(() -> new TaxAgentServiceException(TaxSystemType.REMOTE_SERVICE_CALLS_ARE_EXCEPTIONAL));
Optional.ofNullable(dataPathMap).orElseThrow(() -> new TaxAgentServiceException(TaxSystemType.PARAMETER_IS_NOT_PARSED_CORRECTLY));
dataPathMap.forEach((k, v) -> res.put(k, JsonPath.read(httpResult, v)));
return res;
}
/**
* 解析到map
*
* @param resultObject 结果对象
* @param dataPathMapJson
* @return {@link Map }<{@link String }, {@link Object }>
*/
public static Map<String, Object> parseToMap(Object resultObject, String dataPathMapJson) {
Map<String, Object> res = new HashMap<>();
String httpResult = JsonUtils.toJsonString(resultObject);
Map<String, String> dataPathMap = JsonUtils.fromJsonString(dataPathMapJson, new TypeReference<HashMap<String, String>>() {
});
Optional.ofNullable(httpResult).orElseThrow(() -> new TaxAgentServiceException(TaxSystemType.REMOTE_SERVICE_CALLS_ARE_EXCEPTIONAL));
Optional.ofNullable(dataPathMap).orElseThrow(() -> new TaxAgentServiceException(TaxSystemType.PARAMETER_IS_NOT_PARSED_CORRECTLY));
dataPathMap.forEach((k, v) -> res.put(k, JsonPath.read(httpResult, v)));
return res;
}
}