我想将下面的gson序列化转换为JACKSON序列化。请让我知道我需要改变以使其适用于JACKSON如何使用JACKSON自定义序列化/反序列化?
public class AbstractElementAdapter
implements JsonSerializer<AbstractElement>, JsonDeserializer<AbstractElement>
{
@Override
public JsonElement serialize(AbstractElement src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject();
JsonObject properties = context.serialize(src, src.getClass()).getAsJsonObject();
if (src instanceof TruncatedElement) {
result.add("type", new JsonPrimitive(((TruncatedElement) src).getClassName()));
properties.remove("className");
} else {
result.add("type", new JsonPrimitive(src.getClass().getSimpleName()));
}
result.add("properties", properties);
return result;
}
@Override
public AbstractElement deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String type = jsonObject.get("type").getAsString();
JsonElement element = jsonObject.get("properties");
try {
return context.deserialize(element, Class.forName("com.zreflect.emyed.whiteboard.model.element." + type));
} catch (ClassNotFoundException cnfe) {
throw new JsonParseException("Unknown element type: " + type, cnfe);
}
}
}
如果你有AbstractDocument.AbstractElement?我们只有AbstractElement类。 – user1595858
如果只是使用AbstractElement,它将进入无限循环 – user1595858
对不起,它只是AbstractAlement,自动导入添加了其他 –