1

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?

Dhruv
  • 63
  • 5

2 Answers2

6

@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.

Fernando JS
  • 4,267
  • 3
  • 31
  • 29
Jim Wooley
  • 10,169
  • 1
  • 25
  • 43
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.

Dhruv
  • 63
  • 5
  • Recommend using `bool.TryParse` instead of `bool.Parse` if you don't want an exception thrown in the `FromEntry` implementation. – Jim Wooley Sep 25 '20 at 16:37