POJO for Node with mixed items

68 views
Skip to first unread message

Madhan Raj

unread,
Jun 30, 2016, 12:48:56 AM6/30/16
to jackson-user
<Root ref="abc">
    <Page ref="p1">
        <Object ref="o1"></Object>
        <ObjectGroup ref="o2">
            <Object ref="o1"></Object>
            <Object ref="o2"></Object>
        </ObjectGroup>
        <Object ref="o3"></Object>
        <Object ref="o4"></Object>
    </Page>
</Root>

I want to wite a POJO for the above xml. Asked a question is StackOverFlow

The root will have n Page and Page will have n Object as well as n ObjectGroup and ObjectGroup will have n Object. where n >= 0

I looked into Polymorphic de serialization as well. But How to handle this situation

Hugo Vandeputte

unread,
Jul 4, 2016, 11:16:25 AM7/4/16
to jackson-user

Hello,
You could use the following classes :
A base class Element  mapping the ref string:

public class Element {
   
@JacksonXmlProperty(isAttribute = true)
   
private String ref;
   
   
public String getRef() {
       
return ref;
   
}
}

A Root class:
public class Root extends Element{
   
@JsonProperty(value="Page")
   
@JacksonXmlElementWrapper(useWrapping = false)
   
List<Page> page;
   
   
public List<Page> getPage() {
       
return page;
   
}
}

A page class
public class Page {
   
@JacksonXmlProperty(isAttribute = true)
   
private String ref;
   
   
@JsonProperty(value="Object")
   
@JacksonXmlElementWrapper(useWrapping = false)
   
List<Element> pageObject;
   
   
@JsonProperty(value="ObjectGroup")
   
ObjectGroup objectGroup;

}

And an ObjectGroup class
public class ObjectGroup extends Element{
   
@JsonProperty(value="Object")
   
@JacksonXmlElementWrapper(useWrapping = false)
   
List<Element> elementList;
   
   
public List<Element> getElementList() {
       
return elementList;
   
}
}

And as main testing method:
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
       
// TODO Auto-generated method stub
       
String xmlString="<Root ref=\"abc\">\n" +
               
"    <Page ref=\"p1\">\n" +
               
"        <Object ref=\"o1\"></Object>\n" +
               
"        <ObjectGroup ref=\"o2\">\n" +
               
"            <Object ref=\"o1\"></Object>\n" +
               
"            <Object ref=\"o2\"></Object>\n" +
               
"        </ObjectGroup>\n" +
               
"        <Object ref=\"o3\"></Object>\n" +
               
"        <Object ref=\"o4\"></Object>\n" +
               
"    </Page>\n" +
               
"</Root>";
       
ObjectMapper xmlMapper=new XmlMapper();
       
Root root=xmlMapper.readValue(xmlString, Root.class);
   
}



Reply all
Reply to author
Forward
0 new messages