package testcode; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; 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; /* * This must be defined first, because in python the ValueDeserializer * must be able to refer to this. * This deserializer also needs to refer to the Value class, * which is not yet defined. We therefore use 'Value'. */ /*#PY * from pyson.Deserializer import Deserializer * from decimal import Decimal * * class ValueDeserializer (Deserializer): * def deserialize(self, data:object, clas: object) -> 'Value': * if isinstance(data, float) or isinstance(data, int): * return Value(data) * if isinstance(data,str): * return Value(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()); } } } @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(12f); System.out.println(jackson.writeValueAsString(val)); assertEquals(val, jackson.readValue("12", Value.class)); assertTrue(val.getValue() instanceof Float); 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; } }