4

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?

Subin Sebastian
  • 10,870
  • 3
  • 37
  • 42
KIC
  • 5,887
  • 7
  • 58
  • 98

3 Answers3

5

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;
    }
}
KIC
  • 5,887
  • 7
  • 58
  • 98
2

It seems that you want to customize the serialization, see here.

Gavin Xiong
  • 957
  • 6
  • 9
  • Thanks, this led me into the right direction. Actually it leds me to another question: http://stackoverflow.com/questions/7161638/how-do-i-use-a-custom-serializer-with-jackson So the solution is much more simple using the @JsonValue annontation is enough for me - thanks! – KIC Jan 06 '13 at 10:16
1

First, create a custom serializer for type TestValue.

public class TestValueSerializer extends JsonSerializer<TestValue> {
@Override
public void serialize(TestValue value, JsonGenerator gen, SerializerProvider provider) throws IOException,
        JsonProcessingException {
    gen.writeString(value.toString());
}

}

Then add annotation @JsonSerialize(using=TestValueSerializer.class) before TestValue type.

BTW, even if TestValue had not extended other class, it's better to avoid extending it from Number. Always use implementation inheritance in caution.

Hui Zheng
  • 10,084
  • 2
  • 35
  • 40