Reputation: 3137
I'm having a REST web service that produces a JSON format output from an ArrayList of custom type.
@GET()
@Produces("application/json")
@Path("/ratings")
public List<Rating> getRatings( ) {
Rating rating;
List<Rating> ratings = new ArrayList<Rating>();
rating= new Rating();
//here I set rating object
rating.setNote(...);
// etc....
ratings.add(rating);
//the method returns ratings arraylist
return ratings;
I want to add a parent member to all JSON data like this:
{"ratings":[{"a":"1","b":"test"}]}
and not like:
[{"a":"1","b":"test"}]
Can I do that? Thanks for helping.
Upvotes: 1
Views: 977
Reputation: 76908
The JSON you're asking for is an object that contains a single field (ratings
) that is an array or your Rating
objects. Provided you have POJO JSON support enabled which it seems you do, that's what you have to return if that's what you want.
@XmlRootElement
class Response {
public final List<Rating> ratings;
public Resonse(List<Rating> ratings) {
this.ratings = ratings;
}
}
Change your method signature to return an instance of Response
then:
return new Reponse(ratings);
There's a fairly extensive guide found here
Option B is simply doing the JSON serialization yourself and returning a String
(the JSON).
Upvotes: 3
Reputation: 41
Try it
@Provider
@Produces({MediaType.APPLICATION_JSON})
public class XJsonBodyWriter implements MessageBodyWriter<Object> {
// implement methods
public void writeTo(Object obj, Class<?> clazz, Type type,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> map, OutputStream out)
throws IOException, WebApplicationException {
// serialize it how you want
}
}
Upvotes: 0
Reputation: 1296
If you would like to continue to use Jersey's direct object mapping feature, then yes - creating an object that holds the list of "Ratings" is the best way to go.
Otherwise, you can create a custom serializer. See this example for more details.
Upvotes: 1