0

I have a document in MongoDB which stores monetary data and has the following structure:

{
    "_id": 0
    },
    "data": {
        "value": 283360760.75
    }
}

As double only provides an approximation of the value, "value" is stored as a Decimal128.

I want to import this document into a JsonNode in my Spring Boot app. For most mongodb data types this works perfectly using the following configuration:

    @ReadingConverter
    public class DocumentToJsonNodeConverter implements Converter<Document, JsonNode> {

        private ObjectMapper objectMapper;

        public DocumentToJsonNodeConverter(ObjectMapper objectMapper) {

            this.objectMapper = objectMapper;
        }

        @SneakyThrows
        public JsonNode convert(Document source) {
            return objectMapper.readTree(source.toJson());
        }
    }

For most data types like strings or doubles this works fine and the value is stored in a TextNode/FloatNode where it can be easily used.

I expected Decimal128 values to be stored in a DecimalNode as BigDecimals, however instead they seem to be stored in a TextNode stored within an ObjectNode.

The value as found in JsonNode after being retrieved from MongoDB

Can anyone please explain why this behaviour occurs and what I can try to instead use a DecimalNode?

Sam Meehan
  • 53
  • 5

1 Answers1

1

From the DecimalNode documentation:

Numeric node that contains values that do not fit in simple integer (int, long) or floating point (double) values.

So, the Decimal128_floating-point_format (128 bits for representation) value cannot be contained into a DecimalNode object and then TextNode is instead preferred.

To use DecimalNode instead of TextNode you have to write a custom deserializer or because you already have a JsonNode tree substitute directly the node inside of it.

dariosicily
  • 4,239
  • 2
  • 11
  • 17
  • Ah thanks, so I'm barking up the wrong tree it seems. Could you please provide some more detail about substituting the node inside the JsonNode tree? – Sam Meehan Sep 23 '21 at 08:44
  • @SamMeehan You are welcome. You have to identify the parent node of the textnode, save the value and then set the property of the parent node with the decimalnode with the same value. I made something similar [here](https://stackoverflow.com/questions/68434569/need-to-update-the-value-in-a-json-node/68439806#68439806) and probably it will be something like `((ObjectNode)parent).set(fieldName, new DecimalNode(value));`. – dariosicily Sep 23 '21 at 09:15