首页 > 解决方案 > Apache Camel - 从正文中获取属性值

问题描述

我必须从 POST 调用的主体中获取属性的值。

我想发布这种类型的 JSON:

{"key"   : ["test:testValue"
            "keyTest:value"],
"address": "testAddress",
"type"   : "street"}

在保存实体之前,我想检查“key”属性的值是否包含一个字符串,该字符串的值包含该字符":"- 某种验证。

同时我想确保“类型”的值是枚举列表的一部分——这里也有某种验证。

我尝试使用simple()exchange- 并validator()检查值是否包含:- 但没有任何成功。

如何从 POST 调用的正文中获取键的值?

标签: javahttppostapache-camelmicroservices

解决方案


一个简单的解决方案是首先将 JSON 解组为 POJO,然后使用 Bean 组件 ( https://camel.apache.org/components/latest/bean-component.html ) 验证 POJO。

例子:

.unmarshal().json(JsonLibrary.Jackson, Foo.class)
.bean(new CustomValidator(), "validateFoo")

CustomValidator 可以这样实现(这只是一个示例,您可以根据需要对其进行更新):

public class CustomValidator {
    public void validateFoo(Exchange exchange) {
        Foo foo = exchange.getIn().getBody(Foo.class);
        if (foo == null || !validKeyList(foo.getKey())) {
            // throw exception
        }
    }

    private boolean validKeyList(List<String> values) {
        for (String value : values) {
            if (value.contains(":")) {
                return true;
            }
        }
        return false;
    }

}

为此,您需要添加骆驼杰克逊库(https://mvnrepository.com/artifact/org.apache.camel/camel-jackson)。

您可以在此处找到有关 JSON 解组的信息:https ://camel.apache.org/manual/latest/json.html 。


推荐阅读