2
votes

When trying to Console.Writeline the output of a DynamoDB query (a document), I get "Amazon.DynamoDBv2.DocumentModel.DynamoDBBool" instead of the "true" or "False" value. How to print the correct ToString() representation of any given value coming from DynamoDB whether its a string or int or boolean.

foreach (var resultDocument in resultDocs)
{
    foreach (var resultDocItem in resultDocument)
    {
      printString += $",{resultDocItem.Value.ToString()}";
    }
}

This code prints "Amazon.DynamoDBv2.DocumentModel.DynamoDBBool" when a boolean value is hit rather than 'true' or 'false'

1

1 Answers

3
votes

What you get out of the foreach is a KeyValuePair<string, DynamoDBEntry> which has the default ToString(). To get the string representation of what you actually want you'll need to use the built cast operators to get back to the actual value you're looking for.

Specifically for DynamoDBBool it could look like this:

var doc = new Document();
doc.Add("aaa", new DynamoDBBool(true));
foreach(var item in doc)
{
    var s = item.Value is DynamoDBBool ? item.Value.AsBoolean().ToString() : item.Value.ToString();
    Console.WriteLine($"{item.Key} : {s}");
}

To more easily cover all options we can use the fact that a doc is just a JSON document of key value pairs. This takes the doc to JSON and then prints the proper string representations of each entry.

var doc = new Document();
doc.Add("aaa", new DynamoDBBool(true));
var dict = JsonConvert.DeserializeObject<IDictionary<string, string>>(doc.ToJson());
foreach(var item in dict)
{
    Console.WriteLine(item.Value);
}