package testcode; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.Objects; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; @JsonDeserialize(using = ValueDeserializer.class) public class Value { private final Object value; public Value(Object value) { this.value = value; } public Object getValue() { return value; } /** The test code for Value */ public static void main(String[] args) throws JsonProcessingException { ObjectMapper jackson = new ObjectMapper(); Value val = new Value((float) 12); System.out.println(jackson.writeValueAsString(val)); assertEquals(val, jackson.readValue("12", Value.class)); val = new Value("hallo"); System.out.println(jackson.writeValueAsString(val)); assertEquals(val, jackson.readValue("\"hallo\"", Value.class)); } @Override public int hashCode() { return Objects.hash(value); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Value other = (Value) obj; return Objects.equals(value, other.value); } @Override public String toString() { return "val:" + value; } } class ValueDeserializer extends StdDeserializer { public ValueDeserializer() { this(null); } public ValueDeserializer(Class vc) { super(vc); } @Override public Value deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { String text = jp.getText(); switch (jp.currentToken()) { case VALUE_NUMBER_FLOAT: case VALUE_NUMBER_INT: return new Value(Float.parseFloat(text)); case VALUE_STRING: return new Value(text); default: throw new IOException( "Expected number of double quoted string but found " + text + " of type " + jp.currentToken()); } } }