CustomTypeIdResolver.java
/*
* Copyright 2022 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gringlobal.custom.json;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
import com.fasterxml.jackson.databind.type.TypeFactory;
import java.util.Map;
public abstract class CustomTypeIdResolver implements TypeIdResolver {
private JavaType base;
private Map<String, Class<?>> classes;
@Override
public void init(JavaType javaType) {
base = javaType;
classes = initClassesMap();
}
protected abstract Map<String, Class<?>> initClassesMap();
@Override
public String idFromValue(Object o) {
return o.getClass().getSimpleName();
}
@Override
public String idFromValueAndType(Object o, Class<?> aClass) {
return aClass.getSimpleName();
}
@Override
public String idFromBaseType() {
return idFromValueAndType(null, base.getRawClass());
}
@Override
public JavaType typeFromId(DatabindContext databindContext, String id) {
return TypeFactory.defaultInstance().constructSpecializedType(base, classes.get(id));
}
@Override
public String getDescForKnownTypeIds() {
return String.join(", ", classes.keySet());
}
@Override
public JsonTypeInfo.Id getMechanism() {
return JsonTypeInfo.Id.CUSTOM;
}
}