java - Apache Camel - 从正文中获取属性值
问题描述
我必须从 POST 调用的主体中获取属性的值。
我想发布这种类型的 JSON:
{"key" : ["test:testValue"
"keyTest:value"],
"address": "testAddress",
"type" : "street"}
在保存实体之前,我想检查“key”属性的值是否包含一个字符串,该字符串的值包含该字符":"
- 某种验证。
同时我想确保“类型”的值是枚举列表的一部分——这里也有某种验证。
我尝试使用simple()
或exchange
- 并validator()
检查值是否包含:
- 但没有任何成功。
如何从 POST 调用的正文中获取键的值?
解决方案
一个简单的解决方案是首先将 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 。
推荐阅读
- react-native - react native:渲染字符串和数字数组不起作用
- python - 如何在 django 中对多个字段求和
- go - 有没有办法在go中将一个句子换行/填充到多个句子
- entity-framework - 存储在数据库中的 EF 迁移与原始代码不同
- javascript - HTML 标记到 javascript createElement
- mysql - 在laravel中获取一个标题下相同字符串的所有记录
- typescript - 使用过滤的 keyof 类型索引多态“this”类型
- python - 在 Heroku 上安装 numpy 的问题:找不到满足要求 numpy==1.20.1 的版本(来自 -r /tmp/build_795c7f47/requirements.txt
- asp.net - 如何在VB中的if not语句中使用多个条件
- react-native - React Native Expo 实时聊天功能