Handle BLOB XML Adapter – java.sql.Blob is an interface, and JAXB can’t handle interfaces.

Hi, There:

Started to play with JSON data. When I tried to Marshall my existing Java object which has a java.sql.Blob field,  I got this exception: java.sql.Blob is an interface, and JAXB can’t handle interfaces. etc. After googling, I found the solution is to use an XmlAdapter like this.

import java.sql.Blob;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.hibernate.Hibernate;
public class BlobXmlAdapter extends XmlAdapter<String, Blob> {
@Override
public Blob unmarshal(String v) throws Exception {
if (v ==null) v= “”;
return Hibernate.createBlob(v.getBytes());
}
@Override
public String marshal(Blob v) throws Exception {
if (v == null) return “”;
return v.getBytes(1l, (int)v.length()).toString();
}

}

and annotated it in my POJO’s getter.

@XmlRootElement
public class MyDataObject implements Serializable {

…..

@XmlJavaTypeAdapter(BlobXmlAdapter.class)
public Blob getPAYLOAD() {
return PAYLOAD;
}

……

}

It works like a charm!  My JAX-RS converts the Java into JSON nicely as expected.

-TY

Advertisements