0

我已经实现了以下类,并使用 REST 调用为给定类型的 T 实现了一个搜索方法获取对象列表。

    public class AmapiService<T extends Resource> implements RestService<T> {


    @Override
    public List<T> search( MultivaluedMap<String, String> aQueryParams ) {
          MultivaluedMap<String, String> lQueryParams = aQueryParams;
          Client lClient = buildClient();

      WebTarget ltarget = lClient.target( iRestDriver.target( aApiUrl ).getUri() );

      for ( String lKey : lQueryParams.keySet() ) {
         ltarget = ltarget.queryParam( lKey, lQueryParams.getFirst( lKey ) );
      }

      List<T> lObjects = null;

      lObjects = ltarget.request( MediaType.APPLICATION_JSON ).get( new GenericType<List<T>>() {
      } );

      return lObjects;
   }
}

这就是为类和搜索方法调用创建实例的方式。

AmapiService<RFQDefinition> RFQService =
            new AmapiService<RFQDefinition>();

List<RFQDefinition> qfq = RFQService.search( lQueryParam );

当我运行这个我得到以下错误

May 07, 2018 1:48:14 PM org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor aroundReadFrom
SEVERE: MessageBodyReader not found for media type=application/json, type=interface java.util.List, genericType=java.util.List<T>.

这意味着 RFQDefinition 未设置为new GenericType<List<T>>().

我如何将类型从 T 中设置AmapiService<T extends Resource>new GenericType<List<T>>()

如果我定义它new GenericType<List<RFQDefinition>>()而不是 T 它的工作

4

3 回答 3

1

您对泛型的使用实际上在这里没有任何用途。

没有真正的通用实现,因为您的响应基于您为使用的服务提供的参数 ( .get( new GenericType<List<T>>(){}))。type 参数对此没有帮助,因为代码是由 jax-rs 实现调用的,它不通过静态链接。

换句话说,没有代码会使用参数编译和运行您的类/方法:

//this is not a valid use-case:
List<ActualType> res = search(aQueryParams);

对此的简单翻译可以是:Java 泛型不会进入 REST API。对于 API 应该返回的模型,您必须静态使用 Java 类型(就像您对new GenericType<List<RFQDefinition>>().

于 2018-05-07T18:24:19.137 回答
0

它与泛型无关。

服务器抱怨它没有任何MessageBodyReader可读取的application/json正文。

通常,您可以Jackson为您的应用程序添加 json 解码/编码

读这个:

https://jersey.github.io/documentation/latest/media.html#json.jackson

于 2018-05-07T18:00:48.927 回答
0

我已经像这样更改了搜索方法实现,现在它正在工作。iClass 您可以将其作为参数,例如:RFQDefinition.class

ObjectMapper mapper = new ObjectMapper();
      JavaType type = mapper.getTypeFactory().constructCollectionType( List.class, iClass );
      List<T> lObjects = null;

      JsonArray lResponse = ltarget.request( MediaType.APPLICATION_JSON ).get( JsonArray.class );
      try {
         lObjects = mapper.readValue( lResponse.toString(), type );
      } catch ( JsonParseException e ) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch ( JsonMappingException e ) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch ( IOException e ) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }  
于 2018-05-07T19:50:32.643 回答