我有来自第三方的多种 JSON 格式,需要以统一的方式进行处理。考虑到数据结构未规范化,我无法应用统一的数据处理逻辑。为了实现这一点,我在处理之前寻求将数据格式化为单一格式。
来源1:
{
"fieldName": "status",
"oldValue": "Open",
"newValue": "Closed"
}
来源2:
{
"fieldName": "status",
"oldValue": {
"name": "Open"
},
"newValue": {
"name": "Closed"
}
}
来源3:
{
"fieldName": "reason",
"oldValue": null,
"newValue": {
"name": "Requirements changed"
}
}
来源4:
{
"fieldName": "advertise",
"oldValue": true,
"newValue": false
}
在结果转换中我希望得到以下内容(结合所有来源):
{
"status"|"reason"|"advertise": {
"oldValue": {
"value": "Open"|null|true
},
"newValue": {
"value": "Closed"|"Requirements changed"|false
}
}
}
我正在努力尝试各种 shift 和 default 的组合,但无法实现转换。我尝试构建 JOLT 规范来进行这种转换(见下面的示例),但我无法将不同的字段结构(简单值与对象)放入统一的格式。
[
{
"operation": "shift",
"spec": {
"fieldName": {
"*": {
"@(2,oldValue)": "&1.oldValue",
"@(2,newValue)": "&1.newValue"
}
}
}
}
]
重现问题的代码示例(Java)
package org.example;
import com.bazaarvoice.jolt.Chainr;
import com.bazaarvoice.jolt.JsonUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
var spec = read("src/main/resources/spec.json");
var chainr = Chainr.fromSpec(JsonUtils.jsonToList(spec));
var example1 = read("src/main/resources/example1.json");
var example2 = read("src/main/resources/example2.json");
var example3 = read("src/main/resources/example3.json");
var example4 = read("src/main/resources/example4.json");
for (String source: List.of(example1, example2, example3, example4)) {
System.out.println("===\nSource \n" + source);
var transformedSource = chainr.transform(JsonUtils.jsonToMap(source));
System.out.println("\nAfter transformation \n" +
JsonUtils.toPrettyJsonString(transformedSource));
}
}
private static String read(String path) throws IOException {
return new String(Files.readAllBytes(Paths.get(path)));
}
}
您还需要以下依赖项来实现数据转换
<dependency>
<groupId>com.bazaarvoice.jolt</groupId>
<artifactId>jolt-core</artifactId>
<version>0.1.8</version>
</dependency>
<dependency>
<groupId>com.bazaarvoice.jolt</groupId>
<artifactId>json-utils</artifactId>
<version>0.1.8</version>
</dependency>
有什么想法可以实现它吗?
提前致谢!