package com.atyang.flinlk.udf;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RequestParameterHandler {
private static final Logger logger = LoggerFactory.getLogger(RequestParameterHandler.class);
// 将ObjectMapper实例化为静态常量,避免重复创建
private static final ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] args) {
// 示例JSON字符串
String json = "{\"user\":{\"name\":\"John\",\"address\":{\"city\":\"New York\",\"zip\":\"10001\"},\"skills\":[\"Java\",\"SQL\"]}}";
// 使用示例JSON字符串调用flattenJsonToMap
Map<String, String> flatMap;
try {
flatMap = flattenJsonToMap(json);
// 打印输出结果
flatMap.forEach((key, value) -> System.out.println(key + " = " + value));
} catch (JsonProcessingException e) {
logger.error("Failed to parse JSON: {}", e.getMessage(), e);
// 更具体的异常处理可以在这里实现
} catch (Exception e) {
// 捕获其他异常
logger.error("Unexpected error occurred: {}", e.getMessage(), e);
}
}
public static Map<String, String> flattenJsonToMap(String json) throws JsonProcessingException {
try {
JsonNode rootNode = objectMapper.readTree(json);
Map<String, String> flatMap = new HashMap<>();
StringBuilder prefixBuilder = new StringBuilder(); // 使用StringBuilder优化字符串构建
flattenJsonNode(rootNode, prefixBuilder, flatMap);
return flatMap;
} catch (IOException e) {
// 由于此处明确处理JSON解析异常,因此捕获IOException是合理的
throw new JsonProcessingException("Error parsing JSON", e);
}
}
private static void flattenJsonNode(JsonNode node, StringBuilder prefix, Map<String, String> flatMap) {
if (node.isObject()) {
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
// 使用StringBuilder来构建前缀
prefix.setLength(0); // 清空StringBuilder,避免内存泄漏
prefix.append(prefix.length() > 0 ? "." : "").append(entry.getKey());
flattenJsonNode(entry.getValue(), prefix, flatMap);
}
} else if (node.isArray()) {
// TODO: 逻辑处理以支持数组
logger.warn("Array encountered, but array handling is not implemented.");
} else {
flatMap.put(prefix.toString(), node.asText());
}
}
}
/**
* 自定义异常类,继承自JsonProcessingException,用于更准确地表达JSON处理过程中的错误。
*/
class JsonProcessingException extends Exception {
public JsonProcessingException(String message, Throwable cause) {
super(message, cause);
}
}
json 工具类
最新推荐文章于 2024-07-18 15:45:25 发布