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; } } /*#PY * class ValueDeserializer (Deserializer): * def deserialize(self, data:object, clas: object) -> Value: * if isinstance(data, float) or isinstance(data, int): * return NumberValue(Decimal(str(data))) * if isinstance(data,str): * return DiscreteValue(data) * raise ValueError("Expected number or double quoted string but found " + str(data) * + " of type " + str(type(data))) */ 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()); } } }