0

我有两个 POJO

 @XmlRootElement
 public class PojoBase {
 }

 @XmlRootElement
 public class PojoRequest extends PojoBase {

 private String strTemplate;

 public void setTemplate(String strTemplate) {
    this.strTemplate = strTemplate;
 }

 public String getTemplate() {
    return strTemplate;
 }

 }

 @XmlRootElement
 public class PojoResponse extends PojoBase {

private String strName;

public void setName(String strName) {
    this.strName = strName;
}

public String getName() {
    return strName;
}

}

我有接受基类并将基类作为响应返回的服务。

@POST
@Path("/start")
@Produces({MediaType.APPLICATION_JSON})
@Consumes(MediaType.APPLICATION_JSON)
public PojoBase registerNumber(JAXBElement<PojoBase> theRequest) {
        //does some work with theRequest.

        //here the theRequest object doesn't has pojoRequest data.
        PojoResponse pojoResponse = new PojoResponse();
        pojoResponse.setName("Sample");
        return pojoResponse;
    }

我从客户端发送 pojo 基础对象,但不确定为什么 Restful 没有得到实际的 theRequest 对象。

这是客户端代码:

 public class HttpClient {
    static String _strServiceURL = "http://127.0.0.1:8080/middleware/rest/service/start";
    public static void main(String[] args) throws Exception {

        PojoRequest pojoRequest = new PojoRequest();
        pojoRequest.setTemplate("Somedata");

        PojoBase response = getResponse(pojoRequest);
        PojoResponse pojoresponse = (PojoResponse) response;
        System.out.println(response);
    }

    private static PojoBase getResponse(PojoBase request) {
         try {
             Client client = Client.create();
             WebResource webResource = client.resource(_strServiceURL);
             ClientResponse response = webResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, request);
             System.out.println(response.getStatus()); 
             if(response.getStatus() == 200){
                   PojoBase response =  response.getEntity(PojoBase.class);
                   return response;
             }      
          } catch(Exception e) {
              System.out.println(e.getMessage());
          }
          return null;
      }

}

你能告诉我如何在服务端获取 PojoRequest 吗?

任何帮助表示赞赏。

谢谢

4

1 回答 1

0

我认为您不能像这样将超类传递给球衣。我相信,虽然我可能是错的,但registerNumber()有一个参数JAXBElement<PojoBase> 它会做类似的事情:

  1. 实例化一个 PojoBase
  2. PojoBase对(没有属性)进行反思,因此无需设置。
  3. registerNumber()用实际上是空的PojoBase对象调用

那么为什么不尝试将签名更改为:

public PojoBase registerNumber(JAXBElement< PojoRequest > theRequest) 

甚至(使用 com.sun.jersey.api.json.POJOMappingFeature = true):

public PojoBase registerNumber(PojoRequest theRequest) 
于 2013-12-03T11:44:28.757 回答