I have a JSON node as below from which I need to remove all the values after # like DynamicAttribute#1279930005#ZZ8400 to 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"}
What i tried so far was as below :
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("\\#.*", "\":[");
But the above is giving me only like below and removing the rest of the fields from json :
"{"DynamicAttribute":["
if you are interested in the regex, you can use this: #\\w+#\\w+
to match (and remove) 2 groups of #abc or something like #\\d+#\\w+
if the first one is always going to be numeric:
@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}]}");
}