我想將下面的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,自動導入添加了其他 –