Eknoes
Eknoes

Reputation: 518

Jersey: How to print a generic Object with nested Objects as JSON?

Currently I am printing the Output of my Podcast API like this:

{
  "data":[{"feed":"someUrl","id":1,"name":"someName"}],
  "success":true
}

I have an Response Object for generating the Object with "data" and "success" and I have a PodcastResponse Object for the Podcast Object with "feed", "id", "name".

@XmlRootElement()
@XmlSeeAlso(PodcastResponse.class)
public class Response {
  @XmlElement
  boolean success = true;
  @XmlElement      
  List<PodcastResponse> data;
  //Getters, Setters, etc.
}

@XmlRootElement()
public class PodcastResponse {
  @XmlElement
  int id;
  @XmlElement
  String name;
  @XmlElement
  String feed_url;
  //Getters, Setters, etc.
}

This generates the Output:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getPodcasts() {
  return new Response(true, PodcastManager.getPodcasts());
}

That does work. Now I want to generify the Response class, so that I can use it with more than the PodcastResponse class.

@XmlRootElement()
public class Response<T> {
  @XmlElement
  boolean success = true;
  @XmlElement
  List<T> data;
  //Getters, Setters, etc.
}

That doesnt work as expected, the output:

{
  "data": ["PodcastResponse@93a281a"],
  "success":true
}

How can I write a generic Response Class, so that I can display a varitey of Data in it JSON formatted?

Upvotes: 0

Views: 618

Answers (1)

Use JAXB Annotations that you can use with Jersey to serialize the Java object to XML or JSON. Here is a page which lists how to.

 @XmlRootElement()
 public class PodcastResponse {
   int id;
   String name;
   String feed_url;
   //Getters, Setters, etc.
 }

Upvotes: 2

Related Questions