Reputation: 3224
I've parsed objects like the following, without any issues:
<response>
<myObject>
<id>1</id>
<name>abc</name>
</myObject>
<myObject>
<id>2</id>
<name>def</name>
</myObject>
</response>
with a class like this:
@XmlRootElement(name="myObject")
public class MyObject{
@XmlElement(name="id")
long id;
@XmlElement(name="name")
String name;
/* getters and setters ... etc.. */
}
This works fine, with my API calls I get a list of MyObjects
as expected.
but how do I handle this type of response:
<response>
<objectWrapper>
<myObject>
<id>1</id>
<name>abc</name>
</myObject>
<myObject>
<id>2</id>
<name>def</name>
</myObject>
</objectWrapper>
</response>
At first I thought building an ObjectWrapper
class would do the trick, like this:
@XmlRootElement(name="objectWrapper")
public class ObjectWrapper{
@XmlElement(name="myObject")
List<MyObject> myObject;
/* getters and setters ... etc.. */
}
Then I thought about using @XmlElementWrapper
too, but how?
Can I just remove the @XmlRootElement
from the class and ad @XmlElementWrapper
on the list?
Edit: No, I cannot remove the @XmlRootElement
Upvotes: 0
Views: 391
Reputation: 14238
It doesn't matter if your class is named ObjectWrapper
or not.
You need to specify correct wrapper name in @XmlElementWrapper
which is objectWrapper
.
Your ObjectWrapper
class should look like :
@XmlRootElement( name = "response" )
@XmlAccessorType( XmlAccessType.FIELD )
public class ObjectWrapper
{
@XmlElementWrapper( name = "objectWrapper" )
@XmlElement( name = "myObject" )
private List<MyObject> myObjects;
public void setMyObjects( List<MyObject> objects )
{
this.myObjects = objects;
}
public List<MyObject> getMyObjects()
{
return myObjects;
}
}
Upvotes: 1
Reputation: 10147
You can simply write it like this:
@XmlRootElement(name="response")
public class Response {
@XmlElementWrapper(name="objectWrapper")
@XmlElement(name="myObject")
List<MyObject> myObject;
/* getters and setters ... etc.. */
}
You don't need an ObjectWrapper
class.
Upvotes: 1