DynamoDB ExclusiveStartKey的字典序列化不起作用

问题描述

对于Dynamo的分页响应,我尝试保留ExclusiveStartKey值。在代码示例中,如果我直接使用response.LastEvaluatedKey值,则后续请求可以正常工作。

但是,如果我序列化response.LastEvaluatedKey,然后将其序列化回用作ExclusiveStartKey值,则后续请求将失败,并显示以下错误消息:

提供的起始键无效:一个或多个参数值无效:空属性值类型的值必须为true

反序列化的字典似乎具有与原始字典相同的值...是否有任何检查要检查两者之间的区别?

QueryResponse response = null;

do
{

    string gsiPartitionKey = "gsi-pk-value-1";

    var queryRequest = new QueryRequest()
    {
        TableName = "my-table",IndexName = "my-index",KeyConditionExpression = "IndexPk = :s_gsiPartitionKey",ExpressionAttributeValues = new Dictionary<string,AttributeValue>
        {
            {
                ":s_gsiPartitionKey",new AttributeValue { S = gsiPartitionKey}
            }
        },Limit = 1
    };

    if (response != null)
    {
        //OPTION 1 - OK - Using LastEvaluatedKey directly works fine
        //queryRequest.ExclusiveStartKey = response.LastEvaluatedKey;

        //OPTION 2 - BAD - Serializing and deserializing  fails
        var serialized = JsonConvert.SerializeObject(response.LastEvaluatedKey);
        var deserialized = JsonConvert.DeserializeObject<Dictionary<string,AttributeValue>>(serialized);
        queryRequest.ExclusiveStartKey = deserialized;
    }

    response = await DynamoDbClient.QueryAsync(queryRequest);

} while (response.LastEvaluatedKey.Count != 0);

解决方法

我今天遇到了这个问题,我想我会更新这个。 在 AttributeValue 类中,有一个 _null 类型的非公共成员 bool?,它在从 JSON 反序列化时被错误地初始化。 当它应该设置为 false 时,它被设置为 null

使用反射,反序列化后,我将字典中每个键的值设置为 null,AWS 现在按预期返回数据。

为了访问私有成员,我使用了这个函数:

public void SetPrivatePropertyValue<T>(object obj,string propName,T val)
{
    Type t = obj.GetType();

    // add a check here that the object obj and propertyName string are not null
    foreach (FieldInfo fi in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
    {
        if (fi.Name.ToLower().Contains(propName.ToLower()))
        {
            fi.SetValue(obj,val);
            break;
        }
    }
}

方法调用是 SetPrivatePropertyValue<bool?>(attribute,"_null",null);

祝你好运!

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...