Jolt本地转换返回null但在线工具正常,求解决方案
Jolt转换JSON返回null问题排查与解决
问题场景
需要将以下源JSON转换为目标JSON结构:
源JSON
{ "id": 123, "name": { "firstName": "shiva", "lastName": "kumar" }, "dateOfBirth": "11/09/2012", "emailId": "mymail@gmail.com", "address": { "addressLine1": "blr", "addressLine2": "KA" }, "salary": 12334 }
目标JSON
{ "id": 123, "email": "mymail@gmail.com", "salary": 12334, "fullname": { "firstName": "shiva", "lastName": "kumar" }, "fullAdress": "blr KA" }
使用自定义Java代码执行Jolt转换时返回null,但在线Jolt演示工具可正常完成转换,原代码及依赖配置如下:
原代码
private JSONObject tranformRequest(String json, String specFile){ URI uri = Thread.currentThread().getContextClassLoader().getResource(specFile).toURI(); String jsonSpec = Files.readAllLines(Paths.get(uri)).stream().collect(Collectors.joining()); JSONArray jsonArray = new JSONArray(jsonSpec); List<Map<String, Object>> list = new ArrayList<>(); for(int i = 0 ; i < jsonArray.length();i++){ list.add(jsonArray.getJSONObject(i).toMap()); } Chainr chainr = Chainr.fromSpec(list);// JsonUtils.classpathToList( "/path/to/chainr/spec.json" ); Object output = chainr.transform( json ); return (JSONObject) output; }
原依赖配置
<dependency> <groupId>com.bazaarvoice.jolt</groupId> <artifactId>jolt-core</artifactId> <version>0.1.7</version> </dependency>
问题原因与解决方案
1. 升级老旧的Jolt版本
0.1.7是2014年的老旧版本,存在大量兼容性问题,与在线演示工具使用的新版本语法不匹配,这是转换返回null的核心原因。
修复方式:将Jolt依赖升级到稳定新版本,同时添加json-utils依赖简化配置读取:
<dependency> <groupId>com.bazaarvoice.jolt</groupId> <artifactId>jolt-core</artifactId> <version>0.1.10</version> </dependency> <dependency> <groupId>com.bazaarvoice.jolt</groupId> <artifactId>json-utils</artifactId> <version>0.1.10</version> </dependency>
2. 优化Spec解析逻辑
原代码手动解析JSON Spec为List<Map<String, Object>>,容易出现类型转换或格式错误。使用Jolt内置的JsonUtils工具类可以直接读取classpath中的Spec文件,更可靠。
优化后的代码
private JSONObject transformRequest(String json, String specFile) throws Exception { // 用Jolt工具直接读取classpath中的spec文件 List<Object> specList = JsonUtils.classpathToList(specFile); Chainr chainr = Chainr.fromSpec(specList); // 将输入JSON转为Jolt可处理的对象,执行转换 Object input = JsonUtils.jsonToObject(json); Object output = chainr.transform(input); // 转换为JSONObject返回 return new JSONObject(output); }
3. 确认Jolt Spec的正确性
确保你的Spec符合新版本语法,以下是适配目标JSON的正确Spec:
[ { "operation": "shift", "spec": { "id": "id", "emailId": "email", "salary": "salary", "name": "fullname", "address": { "addressLine1": "fullAdress", "addressLine2": "fullAdress" } } }, { "operation": "modify-overwrite-beta", "spec": { "fullAdress": "=join(' ', @(1,fullAdress))" } } ]
该Spec先通过shift操作映射字段,再用modify-overwrite-beta拼接地址字符串。
验证步骤
- 更新pom.xml中的Jolt依赖版本并添加
json-utils - 替换为优化后的代码
- 确认Spec文件放置在classpath目录下(如resources)
- 执行转换即可得到正确的目标JSON
内容的提问来源于stack exchange,提问作者Shiva
相关产品推荐
相关产品推荐

