1

我正在尝试将颜色编组/解组为 XML。JAXB 项目具有通过 XmlJavaTypeAdapter https://jaxb.java.net/guide/XML_layout_and_in_memory_data_layout.html执行此操作的示例代码。

编组工作正常,输出是我所期望的:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<beanWithColor>
    <foreground>#ff0000ff</foreground>
    <name>CleverName</name>
</beanWithColor>

但是,当尝试从 XML 转到对象时,永远不会调用 unmarshal 方法。任何人都可以提供有关原因的见解吗?解组后,前景色为空,我已经用我的调试器确认 unmarshal 永远不会被调用:

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());
    }
}
}
4

1 回答 1

2

我怀疑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)

您可以在 上设置 aValidationEventHandlerUnmarshaller获取所有故障的挂钩。默认情况下,JAXB impl 不会报告该问题。

修复

ColorAdapter.marshal需要修复该方法以返回正确的值。

String rgb = Integer.toHexString(color.getRGB());
return "#" + rgb.substring(2, rgb.length());
于 2013-05-14T15:39:45.737 回答