JAXB XmlJavaTypeAdapter解组方法不被调用
问题描述:
我正在尝试编组/解组一个Color到XML。 JAXB项目有通过XmlJavaTypeAdapter https://jaxb.java.net/guide/XML_layout_and_in_memory_data_layout.html完成这件事的示例代码。JAXB XmlJavaTypeAdapter解组方法不被调用
的整编工作正常,并输出为我所期望的:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<beanWithColor>
<foreground>#ff0000ff</foreground>
<name>CleverName</name>
</beanWithColor>
然而,试图从XML去反对解组方法时不会被调用。任何人都可以提供洞察力为什么?之后,它是解组前景色为空,我已经与我的调试器,解组是从来没有被称为证实:
BeanWithColor{foreground=null, name='CleverName'}
SCCE:
@XmlRootElement
public class BeanWithColor {
private String name;
private Color foreground;
public BeanWithColor() {
}
public BeanWithColor(Color foreground, String name) {
this.foreground = foreground;
this.name = name;
}
@XmlJavaTypeAdapter(ColorAdapter.class)
public Color getForeground() {
return this.foreground;
}
public void setForeground(Color foreground) {
this.foreground = foreground;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("BeanWithColor{");
sb.append("foreground=").append(foreground);
sb.append(", name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
public static void main(String[] args) {
BeanWithColor bean = new BeanWithColor(Color.blue, "CleverName");
try {
StringWriter writer = new StringWriter(1000);
JAXBContext context = JAXBContext.newInstance(BeanWithColor.class);
final Marshaller marshaller = context.createMarshaller();
marshaller.marshal(bean, writer);
System.out.println("Marshaled XML: " + writer);
final Unmarshaller unmarshaller = context.createUnmarshaller();
BeanWithColor beanWithColor = (BeanWithColor) unmarshaller.unmarshal(new StringReader(writer.toString()));
System.out.println("beanWithColor = " + beanWithColor);
} catch (JAXBException e) {
e.printStackTrace();
}
}
static class ColorAdapter extends XmlAdapter<String, Color> {
public Color unmarshal(String s) {
return Color.decode(s);
}
public String marshal(Color color) {
return '#' + Integer.toHexString(color.getRGB());
}
}
}
答
我怀疑XmlAdapter
正在呼吁unmarshal
但该Color.decode
方法失败(这是我调试代码时发生的情况)。
Color.decode("#ff0000ff");
结果如下:
Exception in thread "main" java.lang.NumberFormatException: For input string: "ff0000ff"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:461)
at java.lang.Integer.valueOf(Integer.java:528)
at java.lang.Integer.decode(Integer.java:958)
at java.awt.Color.decode(Color.java:707)
您可以设置在Unmarshaller
一个ValidationEventHandler
让所有失败的钩子。默认情况下,JAXB impl不会报告该问题。
的修复
ColorAdapter.marshal
该方法需要固定到返回正确的值。
String rgb = Integer.toHexString(color.getRGB());
return "#" + rgb.substring(2, rgb.length());
当你说把一个验证处理程序放在它上面之后,我做了并看到NumberFormatException,并且正在关闭同一个解决方案。 0xff0000ff结束于MAX_INT,Color.decode()调用Integer.decode()。 – Michael 2013-05-14 15:59:16