Skip to content

Instantly share code, notes, and snippets.

@xSAVIKx
Created March 20, 2017 20:54
Show Gist options
  • Save xSAVIKx/71ee2630fd9e6bcfbd8a3b2e595aec72 to your computer and use it in GitHub Desktop.
Save xSAVIKx/71ee2630fd9e6bcfbd8a3b2e595aec72 to your computer and use it in GitHub Desktop.
JAXB Custom Adapter Example
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
/**
* Created by User on 20.03.2017.
*/
public class Demo {
public static void main(String[] args) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(Type.class, InnerType.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Type type = new Type();
type.setId("id");
InnerType value = new InnerType("Pretty Value");
type.setValue(value);
marshaller.marshal(type, System.out);
}
}
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
public class InnerType {
private String value;
public InnerType() {
}
public InnerType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
import javax.xml.bind.annotation.adapters.XmlAdapter;
/**
* Created by User on 20.03.2017.
*/
public class InnerTypeAdapter extends XmlAdapter<String, InnerType> {
@Override
public InnerType unmarshal(String v) throws Exception {
return new InnerType(v);
}
@Override
public String marshal(InnerType v) throws Exception {
return v.getValue();
}
}
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Type {
@XmlElement
private String id;
@XmlJavaTypeAdapter(InnerTypeAdapter.class)
@XmlElement
private InnerType value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public InnerType getValue() {
return value;
}
public void setValue(InnerType value) {
this.value = value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment