在Jersey中如何处理泛型集合

Jersey是一个标准的Restful Web service框架,可以方便的实现Restful的Server端和客户端。

本文主要介绍使用Jersey客户端时如何将Json格式的数组转换成java的List。

例如Json数据:[{"aqi":125,"area":"成都","pm2_5":95,"pm2_5_24h":null,"position_name":"金泉两河","primary_pollutant":null,"quality":"轻度污染","station_code":"1431A","time_point":"2013-10-09T16:00:00Z"},{"aqi":130,"area":"成都","pm2_5":99,"pm2_5_24h":null,"position_name":"十里店","primary_pollutant":null,"quality":"轻度污染","station_code":"1432A","time_point":"2013-10-09T16:00:00Z"}]

Jersey客户端代码:

Response result = target.queryParam("output", "json")
                    .queryParam("city", serviceRequest.getCity())
                    ...
                    .request(MediaType.APPLICATION_JSON_TYPE).get();


            if(result.getStatus() == 200){
                List<RestPm25Item> rsList = result.readEntity(new GenericType<List<RestPm25Item>>(){});

                //RestPm25Item[] rsList = result.readEntity(RestPm25Item[].class);


readEntity方法的参数需要传递泛型对象List的类型,因此如果直接传List.class的话,jersey将默认在List中生成LinkedHashMap对象,而不是我们期望的RestPm25Item。上面红色的两行代码为两种处理的方式均可达到目的。


一些参考:http://aruld.info/handling-generified-collections-in-jersey-jax-rs/

http://jersey.576304.n2.nabble.com/How-can-I-parse-a-java-util-List-lt-gt-Is-it-supported-by-the-Jersey-client-td2300852.html


原文地址:https://www.cnblogs.com/riskyer/p/3359763.html