Reputation: 2645
Given the following class:
public class Customer {
public String name;
public String lastName;
}
I want to generate the following xml output using JAXB for a customer whose name
is John and lastName
is Doe:
<cst>John Doe</cst>
How can i do this with JAXB?
EDIT
The class Customer
is used in several places, as shown here:
public class Sale {
private String productId;
private Date date;
private Customer customer;
}
public class Transaction {
private List<Sale> sales;
}
... and so on... The deal is, how can I tell JAXB: "whenever you see a customer, please use custom formatting"?
My problem is that there are many classes that contain a customer, and I want to programatically control the output (sometimes name + lastname
, sometimes <name>name</name>
, <lastname>lastname</lastname>
) without adding annotations at every class that contains Customer
. This requirement would rule out using JAXBElement<Customer>
.
Upvotes: 1
Views: 1866
Reputation: 15189
You could install an XmlAdapter
that handles the translation:
public static void main(String[] args) throws Exception {
JAXBContext ctxt = JAXBContext.newInstance(CustomerWrapper.class);
Marshaller m = ctxt.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
Customer customer = new Customer("John", "Doe");
m.marshal(new JAXBElement<CustomerWrapper>(new QName("cwrapper"), CustomerWrapper.class, new CustomerWrapper(customer)), System.err);
}
static class CustomerWrapper {
private Customer customer;
public CustomerWrapper() {
}
public CustomerWrapper(Customer customer) {
this.customer = customer;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
@XmlJavaTypeAdapter(CustomerAdapter.class)
static class Customer {
private String name;
private String lastName;
public Customer() {
}
public Customer(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
static class CustomerAdapter extends XmlAdapter<String, Customer> {
@Override
public Customer unmarshal(String v) throws Exception {
String[] ss = v.split(" ");
return new Customer(ss[0], ss[1]);
}
@Override
public String marshal(Customer v) throws Exception {
return v.getName() + " " + v.getLastName();
}
}
outputs
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cwrapper>
<customer>John Doe</customer>
</cwrapper>
Upvotes: 2