我有一个如下所示的 JSON 节点,我需要从中删除#like DynamicAttribute#1279930005#ZZ8400 之后的所有值到 DynamicAttribute
{
"uniqueCode": "ZZ",
"entity": "PROFILE",
"id": "e2b627b360d664377b227b--70378143#1",
"data": [
"DynamicAttribute"
],
"values": {
"DynamicAttribute#1279930005#ZZ8400": [
{
"property": "activeFlag",
"currentState": true,
"previousState": null
}
]
},
"DATE_TIME": "05-Apr-2023 19:17:14.376"}
到目前为止我尝试的是如下:
String eventData; //Has the above json payload
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(eventData);
ObjectNode objectNode = objectMapper.convertValue(jsonNode.get("values"), ObjectNode.class);
objectNode.toString().replaceAll("\\#.*", "\":[");
但上面只给我如下所示,并从 json 中删除其余字段:
"{"动态属性":["
如果你对正则表达式感兴趣,你可以使用这个:
#\\w+#\\w+
匹配(并删除)2组#abc或类似#\\d+#\\w+
的东西如果第一个总是数字:
@Test
void test() throws JsonProcessingException {
String eventData = """
{
"uniqueCode": "ZZ",
"entity": "PROFILE",
"id": "e2b627b360d664377b227b--70378143#1",
"data": [
"DynamicAttribute"
],
"values": {
"DynamicAttribute#1279930005#ZZ8400": [
{
"property": "activeFlag",
"currentState": true,
"previousState": null
}
]
},
"DATE_TIME": "05-Apr-2023 19:17:14.376"
}
""";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(eventData);
ObjectNode objectNode = objectMapper.convertValue(jsonNode.get("values"), ObjectNode.class);
String json = objectNode.toString().replaceAll("#\\w+#\\w+", "");
assertEquals(json, "{\"DynamicAttribute\":[{\"property\":\"activeFlag\",\"currentState\":true,\"previousState\":null}]}");
}