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

标签 c# dictionary serialization amazon-dynamodb jsonconvert

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

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

The provided starting key is invalid: One or more parameter values were invalid: Null attribute value types must have the value of 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 class,有一个非public成员_null类型 bool?从 JSON 反序列化时初始化不正确。 它被设置为 false什么时候应该设置为null .

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

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

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);

祝你好运!

关于c# - DynamoDB ExclusiveStartKey 的字典序列化不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64178120/

相关文章:

c# - 替换现有的 Outlook 日历约会

java - 将可序列化对象传递给 Activity 时的转换无效

java - 尝试返回自定义对象类型时出现 SerializationException

c# - 删除嵌套 TabPage 的代码并不总是有效

c# - 如何从C#中的数组复制所有不同的元素

python - 使用 Gensim 中的 filter_extremes 按频率过滤 token

c# - WebAPI - 使用 json 发布到字典

java - 如何使用ObjectOutputStream.writeObject()+Base64 (Java)深度序列化对象?

c# - 使用 C# 在 Excel 中复制/粘贴单元格

python - 给定一个可以在字典的元组键之间找到的整数,在字典中查找值