Configure Json Output with Jersey and Jaxb

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?

+3
source share
2 answers

ContextResolver, JSONConfiguration JSON. , :

@Provider
public class MyJAXBContextProvider implements ContextResolver<JAXBContext> {

    private JSONJAXBContext trackCtx;

    public MyJAXBContextProvider() throws JAXBException {
        trackCtx = new JSONJAXBContext(JSONConfiguration.mappedJettison().build(), Track.class);
    }

    public JAXBContext getContext(Class<?> type) {
        if(type == Track.class) {
            return trackCtx;
        }

        return null;
    }

}

:

{"track":{"singer":"ABC","title":"XYZ"}}

+3

Track :

public class TrackWrapper {
  Track track;
  TrackWrapper(Track track) {
    this.track=track;
  }
}

TrackWrapper,

@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public Response getTrackInJSON() throws JAXBException
  {
  final TrackWrapper trackWrapper = new TrackWrapper(new Track());
  return Response.status(201).entity(trackWrapper).build();
  }

}

, JSON, JAXB.

+1

All Articles