Link to home
Start Free TrialLog in
Avatar of serrutom
serrutomFlag for Belgium

asked on

Create a custom binder for Jaxb

I have an XML file I want to parse into an object with Jaxb. I have created the objects according to the XML file I receive, and annotated the getters to setup the binding.

The purchase date is coming in as a yyyyMMdd format, and this is not parsed correctly. I searched around a bit, and it seems I need to create a custom Jaxb binder.

Can anyone give me a jump-start on how i need to create this custom binder ?

Thanks
@XmlType(name = "PRODUCTSHORT")
public class ProductShort {
	private String modelCode;
	private String serialNo;
	private MyDate purchaseDate;
 
	@XmlElement(name = "MODEL_CODE")
	public String getModelCode() {
		return modelCode;
	}
 
	public void setModelCode(String modelCode) {
		this.modelCode = modelCode;
	}
 
	@XmlElement(name = "SERIAL_NO")
	public String getSerialNo() {
		return serialNo;
	}
 
	public void setSerialNo(String serialNo) {
		this.serialNo = serialNo;
	}
 
	@XmlElement(name = "PURCHASE_DATE")
	public MyDate getPurchaseDate() {
		return purchaseDate;
	}
 
	public void setPurchaseDate(MyDate purchaseDate) {
		this.purchaseDate = purchaseDate;
	}
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Gibu George
Gibu George
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of serrutom

ASKER

Works perfectly !!!

I created a MyDateXmlAdapter to convert the incoming date (String) to the MyDate class. And on the MyDate class I added following annotation: @XmlJavaTypeAdapter(MyDateXmlAdapter.class)
import java.text.DateFormat;
import java.text.SimpleDateFormat;
 
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlAdapter;
 
@XmlTransient
public class MyDateXmlAdapter extends XmlAdapter<String, MyDate> {
	private DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
 
	@Override
	public MyDate unmarshal(String s) throws Exception {
		if (s != null && s.length() > 0) {
			MyDate dt = new MyDate();
			try {
				dt.setTime(dateFormat.parse(s).getTime());
			} catch (Exception e) {
			}
			return dt;
		} else {
			return null;
		}
	}
 
	@Override
	public String marshal(MyDate date) throws Exception {
		if (date != null) {
			return dateFormat.format(date);
		} else {
			return null;
		}
	}
}

Open in new window