Java – what should JAXB return from the ‘beforemarshal (marshaler)’ method?
First of all, I'm not talking about Marshall #listener
Anyone can tell me what should be returned from the Boolean before Marshal (marshaler) method?
/** * Where is apidocs for this method? * What should I return for this? */ boolean beforeMarshal(Marshaller marshaller);
Anyway, I mean to use this method to convert JPA's long @ ID to JAXB's string @ xmlid, jaxb-ri and Moxy
[Edit] a void version seems to work Is this just a documentation problem?
Solution
Brief answer
Boolean return type is a document error The return type should be invalid
The answer is long
You can use eclipse link JAXB (Moxy) because it has no restriction that the field / property annotated with @ xmlid is of type string
You can use the xmladapter to map the use cases that support you:
IDAdapter
This xmladapter converts a long value to a string value to meet the requirements of the @ xmlid annotation
package forum9629948;
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class IDAdapter extends XmlAdapter<String,Long> {
@Override
public Long unmarshal(String string) throws Exception {
return DatatypeConverter.parseLong(string);
}
@Override
public String marshal(Long value) throws Exception {
return DatatypeConverter.printLong(value);
}
}
B
@The xmljavatypeadapter annotation specifies the xmladapter:
package forum9629948;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlAccessorType(XmlAccessType.FIELD)
public class B {
@XmlAttribute
@XmlID
@XmlJavaTypeAdapter(IDAdapter.class)
private Long id;
}
One
package forum9629948;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class A {
private B b;
private C c;
}
C
package forum9629948;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)public class C {
@XmlAttribute
@XmlIDREF
private B b;
}
demonstration
package forum9629948;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(A.class);
File xml = new File("src/forum9629948/input.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
A a = (A) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
marshaller.marshal(a,System.out);
}
}
Input and output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a>
<b id="123"/>
<c b="123"/>
</a>
