Serializing and Deserializing custom objects using JiBX
Posted by davidnewcomb on 16 Dec 2008 in Techie
JiBX is a framework for binding XML data to Java objects (I stole that from their website!). There are a standard set of converters in the JiBX library that will help you convert your own classes to XML. There is a bit more information in the conversions section of their website.
Converters for all the privative types and some of the standard objects are supported in the class
org.jibx.runtime.Utility
, but some of the newer classes are not. One set of methods which is missing is a serializer and deserializer to convert java.util.UUID
.
Let’s say you want to serialize the following class:
package uk.co.bigsoft.myproj;
import java.util.UUID ;
public class MyClass
{
private UUID ident;
MyClass()
{
//
}
public UUID getIdent()
{
return ident;
}
public void setIdent(UUID u)
{
ident= u;
}
}
You must compile the following JiBX binding:
<?xml version="1.0" encoding="UTF-8"?>
<binding>
<format type="java.util.UUID" serializer="uk.co.bigsoft.formatters.Formatter.fromUUID" deserializer="uk.co.bigsoft.Formatter.formatters.toUUID"/>
<mapping name="myclass" class="package uk.co.bigsoft.myproj.MyClass">
<value name="ident" field="ident"/>
</mapping>
</binding>
JiBX will take the binding and start converting the value mappings. If it recognises the type of the attribute you are trying to convert it will use its own converter, but in this case it will see that MyClass.ident
is a UUID
and use the user defined one.
package uk.co.bigsoft.formatters;
import java.util.UUID ;
public class Formatter
{
public static UUID toUUID (String u)
{
return UUID.fromUUID(u);
}
public static String fromDate (UUID u)
{
return u.toString() ;
}
}
The serializer and deserializer’s names are defined like this: fromType
and toType
, but they can be called anything. The only restriction is that they must be static
.No feedback yet
Form is loading...