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

时间:2014-02-04 17:22:14

标签: java json rest jaxb jersey

我有一个应用程序,我希望它接受XML和JSON,我如何编程返回类型?例如,这是我的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)JUTB是否确定了重新定型类型?

2 个答案:

答案 0 :(得分:4)

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

JAX-RS依赖于Content-Type请求标头来查找正确的JAX-RS提供程序来解组传入的请求。

答案 1 :(得分:1)

这是Jax-RS之美的一部分 - Jaxb注释你的POJO和jax-rs将处理来自xml / json的编组和解组。您不必这样做,提供程序应该处理已定义的子集,其中JSON和XML是其中的一部分。

要回答问题的第二部分 - 返回类型由内容协商过程决定。客户端可以发送“Accept”标头来说明他们想要响应的类型。如果没有来自客户端的“建议”,服务器将尝试选择合适的返回类型。

相关问题