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

jkh*_*jkh 6 c# serialization dictionary amazon-dynamodb jsonconvert

对于 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);
Run Code Online (Sandbox Code Playgroud)

小智 7

我今天遇到了这个问题,我想我会更新这个。在类内部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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

祝你好运!