2012-02-01 82 views
1

我試圖用jaxb對包含圖像的對象進行編組,然後解組它(即保存/加載)。JAXB編組/解組SWT.Image或AWT BufferedImage

有沒有一種方法來存儲該圖像?

我想創建它返回字節數組描述swt.image圖象 - 的函數,但一旦我將其標記爲一個@XmlElement,存儲的過程中出現失敗投擲像這樣的例外:

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions 
JAXB annotation is placed on a method that is not a JAXB property 
    this problem is related to the following location: 
     at @javax.xml.bind.annotation.XmlElement() 

此外,我已經測試將SWT.Image轉換爲AWT.BufferedImage,但我仍然得到相同的異常。

回答

2

您的異常表明您已經對不是訪問器的方法(get/set方法)放置了註釋。下面是使用java.awt.Image屬性的示例:

package forum9094655; 

import java.awt.Image; 

import javax.xml.bind.annotation.XmlRootElement; 

@XmlRootElement 
public class Root { 

    private Image image; 

    public Image getImage() { 
     return image; 
    } 

    public void setImage(Image image) { 
     this.image = image; 
    } 

} 

演示

package forum9094655; 

import java.awt.Image; 
import java.awt.image.BufferedImage; 

import javax.xml.bind.JAXBContext; 
import javax.xml.bind.Marshaller; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContext.newInstance(Root.class); 

     Root root = new Root(); 
     Image image = new BufferedImage(1,1,BufferedImage.TYPE_INT_RGB); 
     root.setImage(image); 

     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.marshal(root, System.out); 
    } 

} 

輸出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<root> 
    <image>iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mNgYGAAAAAEAAHI6uv5AAAAAElFTkSuQmCC</image> 
</root> 
+0

嗨Blaise,問題是我被迫使用SWT圖像,我只能創建引用AWT BufferedImages的訪問函數。有沒有辦法告訴JAXB它必須查找這些函數? – 2012-02-01 11:43:35

+1

@JosepRodríguezLópez - 您可以使用'XmlAdapter'來處理JAXB無法識別的任何類型。一個'XmlAdapter'從JAXB不知道如何映射的類型轉換成它所做的類型。這裏是一個鏈接到一個例子,這是爲喬達時代完成的:http://blog.bdoughan.com/2011/05/jaxb-and-joda-time-dates-and-times.html – 2012-02-01 11:50:30