You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Elasticsearch返回的JSON反序列化为Hit<ObjectNode>?

Elasticsearch Hit反序列化ClassCastException问题解决

问题原因

elasticsearch-java客户端的Hit.of(builder -> builder.withJson(...))方法在反序列化时,会将_source字段封装为客户端内部的JsonDataImpl(实现了JsonData接口),而非直接转换为Jackson的ObjectNode类型。因此调用aHit.source()时直接强转ObjectNode会抛出类型转换异常。

解决步骤

无需修改反序列化方式,只需通过JsonData提供的转换方法将其转为ObjectNode:

  1. 将Hit的泛型声明为JsonData,匹配客户端默认的封装类型
  2. 调用JsonData.to(ObjectNode.class)方法完成类型转换

修改后的代码

String hitJson = "{\"_index\":\"my-index\",\"_id\":\"ID:MYID\",\"_score\":1.0,\"_source\":{\"productCode\":\"MYID\",\"productName\":\"my product\",\"EffDate\":\"01/01/1900\",\"ExpDate\":\"12/31/9999\",\"Status\":\"Active\",\"productId\":1234567,\"_type\":\"my type\",\"type\":\"my type\",\"updateTime\":\"2021-07-08T11:40:18Z\"}}";
InputStream hitInput = new ByteArrayInputStream(hitJson.getBytes());

Hit<JsonData> aHit = Hit.of(builder -> builder.withJson(hitInput));
try {
    JsonData sourceData = aHit.source();
    ObjectNode source = sourceData.to(ObjectNode.class);
    // 可正常使用ObjectNode进行后续操作
} catch (Exception ex) {
    String msg = ex.getMessage();
}

补充说明

如果坚持要直接反序列化为Hit<ObjectNode>,需要自定义客户端的JSON配置,让客户端将_source直接解析为ObjectNode,但上述方式更简洁,适合单元测试场景。

内容的提问来源于stack exchange,提问作者Mansfield

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 02:39:25