Introduction | Example | Serialexable |
Serialex supports a number of field classes. However there may be times when objects with other field classes need to be converted to XML.
Serialex includes a Serialexable
interface that defines two methods:
String marshal() throws MarshalException;
and
void unmarshal(String str) throws UnmarshalException;
If Serialex finds a Serialexable object, it will delegate the marshalling of the object to the object's marshal() implementation. The intent of this method is to prduce a String that describes the object sufficiently so that it can subsequently be unmarshalled by the corresponding unmarshal() implementation.
Here is an example of a Serialexable class. It demonstrates how to marshal and unmarshal a single URL field.
import net.sf.serialex.Serialexable;
import net.sf.serialex.unmarshal.UnmarshalException;
import net.sf.serialex.marshal.MarshalException;
import java.net.URL;
import java.net.MalformedURLException;
public class SerialexableClass implements Serialexable {
private URL url;
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
public String marshal() throws MarshalException {
if (url == null) {
throw new MarshalException("Problem marshalling, e);
}
return url.getProtocol() + '|' + url.getHost() + '|' + url.getFile();
}
public void unmarshal(String str) throws UnmarshalException {
String[] strings = str.split("\\|");
try {
url = new URL(strings[0], strings[1], strings[2]);
} catch (MalformedURLException e) {
throw new UnmarshalException("Problem unmarshalling, e);
}
}
}
If Serialexable.marshal() returns null, the coresponding unmarshal() will not be performed, leaving the field uninitialized.