Reputation: 41
I've been trying for a while to come up with a way to return a custom response object with a data attribute that is either an object or a list. Here are some simplified relevant classes. I'm using Jersey v2.27 and Jackson v2.9+
@XmlRootElement(name = "response")
public class ResponseEnvelope<T> {
private Metadata metadata;
private T data;
public ResponseEnvelope(Metadata metadata, T data) {
this.metadata = metadata;
this.data = data;
}
}
@XmlRootElement
public class Person {
private String name;
private int age;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
}
@XmlRootElement
public class ListWrapper<T> {
private List<T> list;
public ListWrapper(List<T> list) {this.list = list;}
}
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public class PersonResource {
private List<Person> getPeople() {
return Arrays.asList(new Person(20, "Monty Python"), new Person(25, "Brian");
}
@GET
public Response getAllPeople() {
ResponseEnvelope<ListWrapper<Person> response = new ResponseEnvelope<ListWrapper<Person>>(new Metadata(), new ListWrapper(getPeople());
return Response.status(200).entity(response).build();
}
@GET
@Path("{id}")
public Response getExampleById(@PathParam("id") String id) {
ResponseEnvelope<Person> response = new ResponseEnvelope<Person>(new Metadata(), getPeople().get(0));
return Response.status(200).entity(response).build();
}
}
@Provider
@Produces(MediaType.APPLICATION_XML)
public class CustomResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
public CustomResolver() {
try {
this.context = JAXBContext.newInstance(
ArrayList.class,
Person.class,
ListWrapper.class,
ResponseEnvelope.class
);
}
catch (JAXBException e) {
throw new RuntimeException(e);
}
}
@Override
public JAXBContext getContext(Class<?> type) {
return (type.equals(ResponseEnvelope.class)) ? context : null;
}
}
@ApplicationPath("")
public class ServerConfig extends ResourceConfig {
public ServerConfig() {
this.packages(true,"com.example");
this.register(JacksonFeature.class);
}
}
I've tried things from several tutorials/questions, such as from here, here, here, etc. (I've tried a lot...)
I can't seem to get a unified response between the two formats. When I try to use a List
directly as T data
, JAXB complains about not having context for ArrayList (when I do put it in there, it doesn't output the elements themselves).
When I use the GenericEntity
class directly in the response, such as with
GenericEntity<List<Person>> list = new GenericEntity<List<Person>>(people){};
return Response.status(200).entity(list).build();`
The output is correct for both json and xml. However if I use this in my T data
field, I get a JAXB exception that it can't find my resource class (it seems you can't use GenericEntity
in a generic class?).
If I use a generic ListWrapper
class to put my collections in, I'm able to create valid xml and json, and using various annotations (@XmlAnyElement(lax = true)
or @XmlElements({@XmlElement(name = "person", type = Person.class)}
) I can get the XML formatted properly, but the json includes the extra ListWrapper<T> list
property (i.e. {"data": {"list": []}}
, instead of {"data": []}
. I've tried using @JsonUnwrapped
for this, and using @JsonSerialize
with a custom serializer, but I can't seem to flatten it out.
A desired sample response for a response for a unique Person id
{
"metadata": {
// some content
},
"data": {
"age": 20,
"name": "Monty Python"
}
}
and XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
<data>
<age>20</age>
<name>Monty Python</name>
</data>
<metadata>
<!-- some content -->
</metadata>
</response>
and for a list of people:
{
"metadata": {
// some content
},
"data": [
{
"age": 20,
"name": "Monty Python"
},
{
"age": 25,
"name": "Brian"
}
]
}
and XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
<data>
<person>
<age>20</age>
<name>Monty Python</name>
</person>
<person>
<age>25</age>
<name>Brian</name>
</person>
</data>
<metadata>
<!-- some content -->
</metadata>
</response>
Upvotes: 3
Views: 873
Reputation: 41
The answer was to use the ListWrapper<T>
class, and to annotate the getter with @JsonValue
, along with the @XmlAnyElement(lax = true)
. These create the properly formatted JSON and XML responses. The class should look like this
import java.util.List;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonValue;
@XmlRootElement(name = "data")
public class ListWrapper<T> {
private List<T> list;
public ListWrapper() {}
public ListWrapper(List<T> list) {
this.list = list;
}
/**
* @return the list
*/
@XmlAnyElement(lax = true)
@JsonValue
public List<T> getList() {
return list;
}
/**
* @param list
* the list to set
*/
public void setList(List<T> list) {
this.list = list;
}
}
Upvotes: 1