I want to deserialize (unmarshal) simple POJOs directly from an XML string, without any configuration (schema definition or other) file.
My application uses a simple base abstract class Field
as follows:
public abstract class Field
{
private final String name;
private final Object value;
protected Field(String name, Object value)
{
this.name = name;
this.value = value;
}
}
which is extended by various other classes, such as
public class StringField extends Field
{
public StringField(String name, String value)
{
super(name, value);
}
}
Note that there is no no-arg constructor on any of these classes.
A serialized StringField POJO will look something like
<StringField>
<name>test</name><type />
<value>Some text</value>
</StringField>
Assuming that the above XML is stored in a String variable called xml
, I am trying to use JAXB to deserialize, via the following method:
public static Field deserialize(String xml)
{
Field field = null;
try
{
JAXBContext context = JAXBContext.newInstance(Field.class);
javax.xml.bind.Unmarshaller um = context.createUnmarshaller();
field = (Field)um.unmarshal(new StringReader(xml));
}
catch (JAXBException e)
{
e.printStackTrace();
}
return field;
}
Ideally, I would like to have the XML string deserialized into the appropriate Java POJO (i.e., StringField in the above case).
However, I am getting JAXB exceptions because Field does not have a no-arg constructor and, even if I put one there, because it cannot be instantiated.
But even if I make the Field class non-abstract, the values assigned via the default constructor to the 2 fields (name, value) are the ones prevailing, as opposed to the actual values deserialized from the XML string. Even if that worked, I would not get a child object (StringField) but a parent one (Field).
Is there any generic way of dynamically deserializing POJOs, without schema declarations, and getting actual (child) objects using JAXB?