你需要一個自定義的串行器和解串器。有一些預製的modules左右,但我不知道一個處理java.awt.Color
。
這裏的定義串行器/解串器對和註冊一個模塊來處理Color
對象的示例:
public class JacksonColorTest {
public static class ColorSerializer extends JsonSerializer<Color> {
@Override
public void serialize(Color value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeFieldName("argb");
gen.writeString(Integer.toHexString(value.getRGB()));
gen.writeEndObject();
}
}
public static class ColorDeserializer extends JsonDeserializer<Color> {
@Override
public Color deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
TreeNode root = p.getCodec().readTree(p);
TextNode rgba = (TextNode) root.get("argb");
return new Color(Integer.parseUnsignedInt(rgba.textValue(), 16), true);
}
}
public static void main(String [] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Color.class, new ColorSerializer());
module.addDeserializer(Color.class, new ColorDeserializer());
objectMapper.registerModule(module);
Color testColor = new Color(1, 2, 3, 4);
String json = objectMapper.writeValueAsString(testColor);
Color backToObject = objectMapper.readValue(json, Color.class);
if (!testColor.equals(backToObject)) {
throw new AssertionError("round trip failed");
}
}
}
謝謝!我的解決方案與您所做的相似。我使用了很多awt類,它們似乎不是傑克遜開箱即用的兼容類,但我只是爲所有這些類創建了自定義的de/serializers,就像一個魅力一樣。 –