I am trying to create a simple web service that outputs using json, but I am not getting the desired Json output.
POJO: package com.rest.resource;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Track implements Serializable
{
@XmlElement
String singer = "ABC";
@XmlElement
String title = "XYZ";
}
Services:
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBException;
import com.rest.resource.Track;
@Path("/json/metallica")
public class JSONService
{
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Track createTrackInJSON(final Track track)
{
return track;
}
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public Response getTrackInJSON() throws JAXBException
{
final Track track = new Track();
return Response.status(201).entity(track).build();
}
}
On / get, I get
{"singer": "ABC", "name": "XYZ"}
but I want "track": {"singer": "ABC", "title": "XYZ"} I cannot print the root element.
I tried using the CustomJAXBContextResolver class but didn’t work for me? Can someone give an example of the same?
source
share