@Consomme({“application/xml,application/json”}) comment programmer le type de retour

J'ai une application et je veux qu'il accepte de XML et JSON , comment puis-je programmer le type de retour ? par exemple, ceci est mon POJO

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;


//Class to marshall and unmarshall the XML and JSON to POJO

 //This is a class for the request JSON and XML


@XmlRootElement
public class KeyProvision {

    private String Consumer ; 
    private String API ; 
    private String AllowedNames ; 


    public void setConsumer( String Consumer)
    {
        this.Consumer= Consumer;

    }


    public void setAPI( String API){

        this.API = API;

    }


    public void setAllowedNames(String AllowedNames){

        this.AllowedNames = AllowedNames;

    }

     @XmlElement(name="Consumer")
    public String  getConsumer(){

        return Consumer;
    }

     @XmlElement(name="API")
    public String getAPI(){

        return API;
    }

     @XmlElement(name="AllowedNames")
    public String getAllowedNames(){

        return AllowedNames;
    }

}

Mon reste de l'interface est

    import javax.ws.rs.Consumes;
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;

@POST
     @Path("/request")
     @Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
     @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
     public Response getRequest(KeyProvision keyInfo){

    /* StringReader reader = new StringReader(keyInfo); //this code just leads to an execution failure for some reason 
     try{
         JAXBContext jaxbContext = JAXBContext.newInstance(KeyProvision.class);

         Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
         KeyProvision api = (KeyProvision) jaxbUnmarshaller.unmarshal(reader);
         System.out.println(api);

     }   catch(JAXBException e){
         e.printStackTrace();

     }
      */

     String result = "Track saved : " + keyInfo;
     return Response.status(201).entity(result).build() ;

  //  return "success" ;

 }

mon XML est

<?xml version="1.0" encoding="UTF-8"?>
<KeyProvision>
<Consumer> testConsumer </Consumer>
<API>posting</API>
<AllowedNames> google</AllowedNames>
</KeyProvision>

mon JSON est

{
    "KeyProvision": {
        "Consumer": "testConsumer",
        "API": "posting",
        "AllowedNames": "google",

    }
}

Mes problèmes/questions sont

1) je reçois un 415 erreur lorsque j'utilise le JSON , pourquoi ce n'est pas unmarshalling correctement?
2) Est la reuturn type déterminé par JAXB?

Pas en rapport avec votre problème, mais vous devriez envisager de prendre un oeil de plus près à votre setAllowedNames(String) méthode.

OriginalL'auteur user1801279 | 2014-02-04