mongodb - 访问 Camel EIP bean 中消息体的元素
问题描述
我有一个使用 Content Enricher EIP 的骆驼路线。所以我的路线是这样的:
AggregationStrategy aggregationStrategy = new TestAggregationStrategy();
from("timer:myTimer?repeatCount=1")
.setBody(simple("{\"channel\": \"orderbook\", \"market\": \"BTC/USD\", \"type\": \"update\", \"data\": {\"time\": 1626139758.986094, \"checksum\": 195176195, \"bids\": [[32965.0, 0.0], [32962.0, 3.4015]], \"asks\": [], \"action\": \"update\"}}"))
.setHeader(MongoDbConstants.CRITERIA, constant(Filters.eq("market", "BTC/USD")))
.enrich("mongodb:mongo?database=dev&collection=order&operation=findOneByQuery", aggregationStrategy)
.log("Test: ${body}");
在 TestAggregationStrategy 我有两个交换,原始的和资源的。
public class TestAggregationStrategy implements AggregationStrategy {
public Exchange aggregate(Exchange original, Exchange resource) {
System.out.println("Original: " + original.getMessage().getBody().toString());
String bidsJsonQuery = "$.data.bids";
DocumentContext updateContext = JsonPath.parse(original.getMessage().getBody().toString());
List<String> updateJsonString = updateContext.read(bidsJsonQuery);
System.out.println(resource.getMessage().getBody());
//ArrayList test = (ArrayList) resource.getMessage().getBody(List.class);
Object test = resource.getMessage().getBody();
System.out.println("Test: " + test);
System.out.println("Resource: " + resource.getMessage().getBody());
return resource;
}
}
我可以使用resource.getMessage().getBody() 获取消息内容,它返回某种对象。如果我将它放入 println() 中,它会打印 Mongo 文档。当我使用调试器检查资源交换时,它看起来像这样:
交换 > 在 > 正文(“文档”)
其中包含一个哈希映射数组。在此示例中,其中一个哈希映射的键为“bids”,其值为数组列表。
您可以直接访问这些值吗?数组列表?我一直在试验,但我无法通过 getBody()。
解决方案
您的代码(Jsonpath 查询和转换)没问题,但“出价”不是List<String>
在您设置的消息正文中,“出价”是一个List<List<Double>>
.
当我获取您的 Json 字符串时,我可以像这样在纯 Java 中提取“出价”
String jsonString = "{\"channel\": \"orderbook\", \"market\": \"BTC/USD\", \"type\": \"update\", \"data\": {\"time\": 1626139758.986094, \"checksum\": 195176195, \"bids\": [[32965.0, 0.0], [32962.0, 3.4015]], \"asks\": [], \"action\": \"update\"}}";
String bidsJsonQuery = "$.data.bids";
DocumentContext updateContext = JsonPath.parse(jsonString);
List<List<Double>> bids = updateContext.read(bidsJsonQuery);
for (List<Double> bid : bids) {
for (Double singleBid : bid) {
logger.info("{}", singleBid);
}
}
记录器的输出是
32965.0
0.0
32962.0
3.4015
顺便说一句:在您的代码中,您解析original
消息正文。在你写的关于resource
身体的文本中。这是您的代码中的错误吗?
推荐阅读
- opencv - AttributeError:尽管使用“opencv_extras”配方,模块'cv2'没有属性'face'
- c# - Azure 存储 Blob 下载进度指示器
- google-api - 检索 Google 共享驱动器文件夹的网络视图链接
- node.js - 如何部署 azure webapp 以便安装节点模块
- xamarin - 在路径上找不到类“com.onesignal.GcmBroadcastReceiver”:DexPathList
- php - 在表格的 ASC 和 DESC 排序之间切换
- java - CompletableFuture - 我如何触发异常?
- mongodb - 在 mongoDB 指南针中连接到 localhost 时出错
- amazon-redshift - Amazon Redshift 中 LISTAGG 函数的替代方法
- dialogflow-es - 如何使用 facebook messenger 进行 Dialogflow 集成?