2017-02-06 42 views
3
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對象映射器對java.awt.color類進行序列化。取出生成的json字符串並將其反序列化回java.awt.color類。但是,在執行反序列化時會發生以下錯誤。無法使用jackson解串器反序列化java.awt.color

異常在線程「主」 com.fasterxml.jackson.databind.JsonMappingException:找到類型沒有合適的構造[簡單類型,類java.awt.Color]:不能從JSON對象實例化

回答

3

你需要一個自定義的串行器和解串器。有一些預製的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"); 
     } 
    } 
} 
+0

謝謝!我的解決方案與您所做的相似。我使用了很多awt類,它們似乎不是傑克遜開箱即用的兼容類,但我只是爲所有這些類創建了自定義的de/serializers,就像一個魅力一樣。 –

相關問題