Reputation: 6121
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?
Upvotes: 4
Views: 2043
Reputation: 10224
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.
Upvotes: 1
Reputation: 6121
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;
}
}
Upvotes: 5
Reputation: 977
It seems that you want to customize the serialization, see here.
Upvotes: 2