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

Java如何将DynamoDB扫描返回的AttributeValues展示到表格?

解决DynamoDB AttributeValue动态类型解析问题

核心思路

写一个通用工具方法,通过判断AttributeValue的实际类型,提取对应的值,既避免直接toString()返回带类型标记的字符串,也解决特定类型方法(如s())在类型不匹配时返回null的问题。

完整代码示例

1. 编写AttributeValue解析工具方法

private static Object parseAttributeValue(AttributeValue attrValue) {
    // 字符串类型
    if (attrValue.s() != null) {
        return attrValue.s();
    }
    // 数字类型(可按需转成Integer/Long/Double,这里保留字符串避免精度丢失)
    else if (attrValue.n() != null) {
        return attrValue.n();
    }
    // 布尔类型
    else if (attrValue.bool() != null) {
        return attrValue.bool();
    }
    // 列表类型,递归解析内部元素
    else if (attrValue.l() != null) {
        List<Object> parsedList = new ArrayList<>();
        for (AttributeValue item : attrValue.l()) {
            parsedList.add(parseAttributeValue(item));
        }
        return parsedList;
    }
    // 嵌套Map类型,递归解析内部键值对
    else if (attrValue.m() != null) {
        Map<String, Object> parsedMap = new HashMap<>();
        for (Map.Entry<String, AttributeValue> entry : attrValue.m().entrySet()) {
            parsedMap.put(entry.getKey(), parseAttributeValue(entry.getValue()));
        }
        return parsedMap;
    }
    // 二进制类型,转成Base64字符串方便展示
    else if (attrValue.b() != null) {
        return Base64.getEncoder().encodeToString(attrValue.b().array());
    }
    // 兜底处理未覆盖的类型(如SS/NS/BS集合等)
    return attrValue.toString();
}

2. 修改遍历代码,应用解析方法

// 假设items是你扫描得到的List<Map<String, AttributeValue>>
List<String> tableRows = new ArrayList<>();
for (Map<String, AttributeValue> itemMap : items) {
    StringBuilder rowContent = new StringBuilder();
    for (Map.Entry<String, AttributeValue> entry : itemMap.entrySet()) {
        Object plainValue = parseAttributeValue(entry.getValue());
        rowContent.append(entry.getKey()).append(": ").append(plainValue).append(", ");
    }
    // 移除末尾多余的逗号和空格
    if (rowContent.length() > 0) {
        rowContent.setLength(rowContent.length() - 2);
    }
    tableRows.add(rowContent.toString());
}

// 后续可将tableRows中的内容渲染到表格中

关键细节说明

  • 类型判断优先级:优先处理常见的基础类型(字符串、数字、布尔),再处理嵌套结构和特殊类型,符合业务场景的使用频率
  • 递归处理嵌套数据:针对List和Map类型的AttributeValue,递归调用解析方法,确保嵌套层级的数据也能正确提取为普通值
  • 类型转换灵活性:数字类型默认保留字符串形式,避免大整数或高精度小数转成数值类型时丢失精度,可根据业务需求修改为Integer.parseInt()或Double.parseDouble()
  • 兜底逻辑:遇到未覆盖的类型时返回toString()结果,避免出现null导致表格展示异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:10:52