I am using JAXB to convert my domain-model to XML and JSON representations.
I have Student pojo to convert to XMl/JSON. It has an content
property which can be of any data type.
Schema definition for it:
<xs:element name="content" type="xs:anyType" />
Thus the java file generated has Object
type for content.
Student.java:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"content"
})
@XmlRootElement(name = "student")
public class Student
extends People
{
................
@XmlElement(required = true)
protected Object content;
}
I marshall using the following code:
Marshall:
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "name-binding.xml");
this.ctx = JAXBContext.newInstance("packagename",
packagename.ObjectFactory.class.getClassLoader(), properties);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE,media-type);
marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT,true);
marshaller.setProperty(MarshallerProperties.JSON_REDUCE_ANY_ARRAYS, true);
StringWriter sw = new StringWriter();
marshaller.marshal(object, sw);
XML:
<student>
<name>Jack n Jones</name>
<content xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">Sid</content>
</student>
xmlns:xsi
and xsi:type="xsd:string">
are coming appended in the content element. I don't want this type information in my XML.
Similarly for JSON it adds the type info:
JSON:
{
"name" : "Jack n Jones",
"content" : {
"type" : "string",
"value" : "Sid"
}
}
How can I remove the type information and generate XML/JSON according to it's type at run time. So whatever type is content
it get's converted to the type without type information
For example if content is String
then XML:
<student>
<name>Jack n Jones</name>
<content>Sid</content>
</student>