public class TestJacksonColor {
public static void main(String [] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Color black = new Color(0, 0, 0);
String json = objectMapper.writeValueAsString(black);
Color backToObject = objectMapper.readValue(json, Color.class);
}
}
代码尝试使用jackson objectmapper将java.awt.color类序列化。获取生成的json字符串并将其反序列化为java.awt.color类。但是,在执行反序列化时会发生以下错误。
线程中的异常" main" com.fasterxml.jackson.databind.JsonMappingException:找不到类型[simple type,class java.awt.Color]的合适构造函数:无法从JSON对象实例化
答案 0 :(得分:4)
您需要自定义序列化程序和反序列化程序。有一些预先构建的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");
}
}
}
个对象的示例:
{{1}}