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

IAmazonDynamoDB.QueryAsync查询后Document.FromAttributeMap序列化异常求助

问题解决:DynamoDB Document.FromAttributeMap序列化后为空对象

问题原因

Document.FromAttributeMap 处理单值类型(比如你的endDate是字符串类型S)时,没有正确识别属性的类型标识,导致自带的ToJson()方法无法输出有效值。这是因为Document内部存储依赖明确的类型标记,而直接从AttributeMap转换时,部分单值类型的标记未被正确初始化。

解决方法

方案1:直接转自定义模型(推荐)

用AWS SDK的DynamoDBContext直接把AttributeMap转成你的自定义模型,跳过Document中转:

var dynamoDbContext = new DynamoDBContext(_amazonDynamoDb);
var customModel = dynamoDbContext.FromAttributeMap<YourCustomModel>(item);
_logger.LogInformation(JsonSerializer.Serialize(customModel));

记得给自定义模型加上DynamoDB特性标记:

[DynamoDBTable("你的表名")]
public class YourCustomModel
{
    [DynamoDBProperty("endDate")]
    public DateTime EndDate { get; set; }
    // 其他属性...
}

方案2:替换Document的序列化方式

如果必须用Document,别用它自带的ToJson(),改用JsonSerializer直接序列化:

var itemAsDocument = Document.FromAttributeMap(item);
_logger.LogInformation(JsonSerializer.Serialize(itemAsDocument));

另外,检查并升级AWSSDK.DynamoDBv2到最新版本,旧版本可能存在转换bug。

方案3:手动构建Document

如果前两种方法都不行,手动遍历AttributeMap构建Document,确保每个属性类型被正确识别:

var itemAsDocument = new Document();
foreach (var kvp in item)
{
    var attrValue = kvp.Value;
    if (!string.IsNullOrEmpty(attrValue.S))
    {
        itemAsDocument[kvp.Key] = attrValue.S;
    }
    else if (attrValue.N != null)
    {
        itemAsDocument[kvp.Key] = decimal.Parse(attrValue.N);
    }
    // 按需处理布尔、列表等其他类型
}
_logger.LogInformation(itemAsDocument.ToJson());

内容的提问来源于stack exchange,提问作者The-IT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 19:52:47