java – @Consumes({“application / xml,application / json”})如何编程返回类型

我有一个应用程序,我希望它接受XMLJSON,我如何编程返回类型?例如,这是我的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;
    }

}

我的休息界面是

    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" ;

 }

我的XML是

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

我的JSON是

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

    }
}

我的问题是

1)当我使用JSON时,我一直收到415错误,为什么这不能正确解组?
2)JAXB是否确定了重新定型类型?

解决方法:

415 Unsupported Media Type通常是因为,在您的客户端请求中,您没有设置正确的媒体类型标头.在这种情况下,您需要在XML或JSON请求中使用Content-Type:application / xml或Content-Type:application / json.

JAX-RS依赖于Content-Type请求标头来查找正确的JAX-RS Provider以解组传入的请求.

上一篇:如何使用Jersey Rest Webservices和Java解析JSON数组


下一篇:java – 解析媒体类型’application / json; encoding = utf8,charset = utf-8’时出错