Skip to content
NodeTypeJsonResolver.java 1.41 KiB
Newer Older
Sara Bertocco's avatar
Sara Bertocco committed
package it.inaf.oats.vospace.datamodel;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;
import net.ivoa.xml.vospace.v2.Node;

/**
 * This class is called during JSON serialization and deserialization and it is
 * necessary to keep the vos prefix in the type property when performing a
 * conversion between XML and JSON and considering also the inheritance of the
 * Node class.
 *
 * The Node class must be annotated in this way:
 *
 * @JsonTypeInfo(use = JsonTypeInfo.Id.CUSTOM, property = "type", include =
 * JsonTypeInfo.As.EXISTING_PROPERTY)
 * @JsonTypeIdResolver(NodeTypeJsonResolver.class)
 */
public class NodeTypeJsonResolver extends TypeIdResolverBase {

    @Override
    public String idFromValueAndType(Object o, Class<?> type) {
        return idFromValue(o);
    }

    @Override
    public String idFromValue(Object o) {
        Node node = (Node) o;
        return node.getType();
    }

    @Override
    public JsonTypeInfo.Id getMechanism() {
        return JsonTypeInfo.Id.NAME;
    }

    @Override
    public JavaType typeFromId(DatabindContext context, String id) {
        String noPrefixId = id.replace("vos:", "");
        return context.getTypeFactory().constructFromCanonical("net.ivoa.xml.vospace.v2." + noPrefixId);
    }
}