使用 Jaca JsonPath 从 JSON 响应中排除项目

Using Jaca JsonPath to exclude items from JSON response

我正在使用 JsonSmartJsonProvider,我的 JSON 看起来像这样

  {
  "info": {
    "clientCount": 1,
    "compactorVersion": 2,
    "processMonitor": {
      "processList": [
        {
          "name": "java.exe",
          "commandLine": "",
          "pid": 6224
        }
      ]
    }
  }
}

我试图排除“processList”,但保留其他所有内容。我尝试了 $.info[?(@ noneof ['processMonitor'])] 的变体,但我总是以“信息”在响应中为空而告终。是否可以使用 JsonPath 来执行此操作?用于执行此操作的代码如下所示:

        DocumentContext document = JsonPath.using(CONFIGURATION).parse(json);
        
        Map<String, Object> result = new HashMap<>();
        paths.forEach((key, value) -> result.put(key, document.read(value)));
        return result;

如前所述,您实际上是在寻找 JSON 转换。 JOLT 是一个通用库,可以做到这一点。解决方案可能如下所示:

import java.util.List;
import com.bazaarvoice.jolt.Chainr;
import com.bazaarvoice.jolt.JsonUtils;
 
public class MyJsonTransformer {
    public static void main(String[] args) throws Exception {
        List<Object> specs = JsonUtils.classpathToList("/spec.json");
        Chainr chainr = Chainr.fromSpec(specs);
 
        Object inputJSON = JsonUtils.classpathToObject("/input.json");
        Object transformedOutput = chainr.transform(inputJSON);
        System.out.println(JsonUtils.toPrettyJsonString(transformedOutput));
    }
}

还有像这样的 jolt remover 规范文件:

[
  {
    "operation": "remove",
    "spec": {
      "info": {
        "processMonitor": {
          "processList": ""
          }
        }
      }
    }
]

您可以根据自己的意见和上述规范在线试用 JOLT here。很整洁。
JSON 和 spec 也可以内联定义。我还没有端到端测试过。