Java中使用JayWay JSON Path实现Path映射转JSON串的问题
解决方案
方案一:使用JayWay JsonPath 2.7/2.8版本API实现
JayWay 2.7/2.8版本虽然没有Option.CREATE_MISSING_PROPERTIES_ON_DEFINITE_PATH选项,但默认调用set方法时会自动创建缺失的路径节点。具体实现如下:
依赖配置(Maven)
<dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>2.8.0</version> </dependency>
代码实现
import com.jayway.jsonpath.JsonPath; import net.minidev.json.JSONObject; import java.util.HashMap; import java.util.Map; public class JsonPathMapConverter { public static void main(String[] args) { Map<String, String> jsonMap = new HashMap<>(); jsonMap.put("Customer.Account.Number", "1234"); jsonMap.put("Customer.Account.type", "Checking"); // 初始化空JSON对象 JSONObject rootJson = new JSONObject(); // 遍历键值对,逐个设置JSON路径对应的值 for (Map.Entry<String, String> entry : jsonMap.entrySet()) { JsonPath.parse(rootJson).set(entry.getKey(), entry.getValue()).json(); } // 输出最终JSON字符串 System.out.println(rootJson.toJSONString()); } }
执行后输出:
{"Customer":{"Account":{"Number":"1234","type":"Checking"}}}
如果需要将数值类型(如1234)转为JSON数字而非字符串,可在设置值时添加类型判断转换。
方案二:手动解析路径构建嵌套Map,再转JSON
如果不想依赖JayWay,可手动拆分JSON路径,构建嵌套Map结构,再用Jackson/Gson等库转为JSON字符串,这种方式不受第三方库版本限制,更灵活。
依赖配置(以Jackson为例,Maven)
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency>
代码实现
import com.fasterxml.jackson.databind.ObjectMapper; import java.util.HashMap; import java.util.Map; public class ManualPathConverter { public static void main(String[] args) throws Exception { Map<String, String> jsonMap = new HashMap<>(); jsonMap.put("Customer.Account.Number", "1234"); jsonMap.put("Customer.Account.type", "Checking"); Map<String, Object> rootMap = new HashMap<>(); for (Map.Entry<String, String> entry : jsonMap.entrySet()) { String[] pathParts = entry.getKey().split("\\."); Map<String, Object> currentLevel = rootMap; // 遍历路径段,创建缺失的嵌套Map for (int i = 0; i < pathParts.length - 1; i++) { String part = pathParts[i]; currentLevel = (Map<String, Object>) currentLevel.computeIfAbsent(part, k -> new HashMap<>()); } // 设置最终节点值,按需做类型转换 String lastPart = pathParts[pathParts.length - 1]; if (entry.getValue().matches("\\d+")) { currentLevel.put(lastPart, Integer.parseInt(entry.getValue())); } else { currentLevel.put(lastPart, entry.getValue()); } } // 转为JSON字符串 ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(rootMap); System.out.println(jsonString); } }
执行后输出符合预期的JSON:
{"Customer":{"Account":{"Number":1234,"type":"Checking"}}}
内容的提问来源于stack exchange,提问作者user2792012
相关产品推荐
相关产品推荐

