regex 正则表达式从Json节点中删除特殊字符

3z6pesqy  于 2023-04-13  发布在  其他
关注(0)|答案(1)|浏览(129)

我有一个JSON节点,如下所示,我需要从其中删除#之后的所有值,如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中删除了其余的字段:
“{“动态属性”:[”

9vw9lbht

9vw9lbht1#

如果你对正则表达式感兴趣,你可以使用这个:#\\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}]}");
}

相关问题