I’m using app engine datastore so I have entity like this.
@PersistenceCapable
public class Author {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@JsonProperty("id")
@JsonSerialize(using = JsonKeySerializer.class)
@JsonDeserialize(using = JsonKeyDeserializer.class)
private Key key;
....
}
When the model is sent to view, it will serialize the Key object as an Id value. Then, if I send data back from view I want to deserialize the Id back to Key object by using JsonKeyDeserializer class.
public class JsonKeyDeserializer extends JsonDeserializer<Key> {
@Override
public Key deserialize(JsonParser jsonParser, DeserializationContext deserializeContext)
throws IOException, JsonProcessingException {
String id = jsonParser.getText();
if (id.isEmpty()) {
return null;
}
// Here is the problem because I have several entities and I can't fix the Author class in this deserializer like this.
// I want to know what class is being deserialized at runtime.
// return KeyFactory.createKey(Author.class.getSimpleName(), Integer.parseInt(id))
}
}
I tried to debug the value in deserialize’s parameters but I can’t find the way to get the target deserialized class. How can I solve this?
You may have misunderstood the role of
KeySerializer/KeyDeserializer: they are used for JavaMapkeys, and not as generic identifiers in database sense of term “key”.So you probably would need to use regular
JsonSerializer/JsonDeserializerinstead.As to type: it is assumed that handlers are constructed for specific types, and no extra type information is passed during serialization or deserialization process: expected type (if handlers are used for different types) must be passed during construction.
When registering general serializers or deserializers, you can do this when implementing
Module, as one of the arguments is type for which (de)serializer is requested.When defining handlers directly for properties (like when using annotations), this information is available on
createContextual()callback of interfaceContextualSerializer(and -Deserializer), if your handler implements it:BeanPropertyis passed to specify property (in this case field with annotation), and you can access its type. This information needs to be stored to be used during (de)serialization.EDIT: as author pointed out, I actually misread the question: KeySerializer is the class name, not annotation.