Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson: treat object as primitive

Tags:

java

jackson

I have a class which is more or less a wrapping class around a double. When I serialize my class via jackson I will receive something like: { "value" : 123.0 }. What I basically would like to happen is, that jackson gives me just 123.0. My problem would be solved if I could extend Number, but since I am already extending another class this is not an option.

Class:

@JsonIgnoreProperties(ignoreUnknown = true)
@SuppressWarnings("unused")
public class TestValue {
    @JsonProperty
    private final Double d;

    public TestValue(Double d) {
        this.d = d;
    }
}

Results in:

{
  "d" : 123.0
}

What would work like expected:

public class TestValue extends Number {
    private final Double d;

    public TestValue(Double d) {
        this.d = d;
    }

    public double doubleValue() {
        return d;
    }

    public float floatValue() {
        return d.floatValue();
    }

    public int intValue() {
        return d.intValue();
    }

    public long longValue() {
        return d.longValue();
    }

    public String toString() {
        return d.toString();
    }
}

.. which results in: 123.0

But - you know - I am already extending an other abstract class. How can I get the expteced result?

like image 489
KIC Avatar asked Feb 17 '23 23:02

KIC


1 Answers

Since I am sure somene can reuse this, I will answer my own question (with thanks to Gavin showing me the way):

public class TestValue {
    private final Double d;

    public TestValue(Double d) {
        this.d = d;
    }

    @JsonValue
    public Double getValue() {
        return d;
    }
}
like image 171
KIC Avatar answered Feb 27 '23 08:02

KIC