Skip to content

Java float deserialized as DoubleNode instance #28

@teabot

Description

@teabot

When parsing JSON documents with a schema described by suitably annotated Java POJO classes, Jackson represents float values with DoubleNode instances, not FloatNode instances as might be expected. This causes problems with other downstream libraries that attempt to interpret the node tree. There are situations where they may call isFloat() on the respective nodes, expecting it to return true for nodes that were derived from float properties. However, in these circumstances DoubleNode.isFloat() is invoked yielding a return value of false and causing said libraries to raise an error.

I believe I have traced this behaviour back to: com.fasterxml.jackson.databind.deser.std.BaseNodeDeserializer._fromFloat(...)

The last call to the nodeFactory returns a DoubleNode not a FloatNode. I wonder if this should instead be implemented in a similar manner to _fromInt(...) like so:

    protected final JsonNode _fromFloat(JsonParser p, DeserializationContext ctxt,
            final JsonNodeFactory nodeFactory) throws IOException
    {
        JsonParser.NumberType nt = p.getNumberType();
        if (nt == JsonParser.NumberType.BIG_DECIMAL
            || ctxt.isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)) {
            return nodeFactory.numberNode(p.getDecimalValue());
        }
        if (nt == JsonParser.NumberType.DOUBLE) {              // PROPOSED CHANGE
            return nodeFactory.numberNode(p.getDoubleValue()); // PROPOSED CHANGE
        }                                                      // PROPOSED CHANGE
        return nodeFactory.numberNode(p.getFloatValue());      // PROPOSED CHANGE
    }

I am currently working around this by patching the downstream library to do something like this:

if (node.isDouble() && node.doubleValue() >= -Float.MAX_VALUE
    && node.doubleValue() <= Float.MAX_VALUE || node.isFloat()) {
        return datum.floatValue();

Reference: problem discussion on jackson-user

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions