'C# Equivalant of Javas @DynamoDBTyped(DynamoDBAttributeType.BOOL)

I had this question but there was no C# answer, only Java ones (DyanmoDb is storing value 1 instead of boolean value true) so posting this.

There is no way I know of that allows you to use the Object Persistence model for DynamoDB and ensure that boolean primitives stay "true"/"false" when put in a DynamoDB table. By default, they get turned into "1" and "0".

How can we ensure that a boolean field doesn't get turned into a 1/0 when put in DynamoDB?



Solution 1:[1]

@Dhruv's original converter saves as a string value rather than native bool. You can modify your property converter slightly to use the DynamoDBBool type and still use the document model as follows:

    public class DynamoDBNativeBooleanConverter : IPropertyConverter
    {
        public DynamoDBEntry ToEntry(object value) => new DynamoDBBool(bool.TryParse(value?.ToString(), out var val) && val);
        public object FromEntry(DynamoDBEntry entry) => entry.AsDynamoDBBool()?.Value;
    }

This could be extended more to support for reading from string/number/etc in the FromEntry to handle legacy data scenarios if desired.

Solution 2:[2]

The one way we can do this is to use IPropertyConverter.

First, we need to create a class that extends the IPropertyConverter, and put in our desired logic. We need to describe the to and from logic.

public class DynamoDBNativeBooleanConverter : IPropertyConverter
    {
        public DynamoDBEntry ToEntry(object value) => (bool) value ? "true" : "false";

        public object FromEntry(DynamoDBEntry entry)
        {
            var val = bool.Parse(entry.AsPrimitive().Value.ToString());
            return val;
        }
    }

Then, we can use this class when we use our boolean attribute:

   ...
        
   [JsonProperty("can_flip")]
   [DynamoDBProperty("can_flip", typeof(DynamoDBNativeBooleanConverter))]
   public bool CanFlip { get; set; }
        
   ...

Using this, the data in DynamoDB tables will show up as "true" or "false", and when you consume it, it will be a boolean.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fernando JS
Solution 2 Dhruv