[英]Parse JSON array from a response body using Resteasy and Jackson annotations
I'm using Resteasy with Quarkus, and Jackson annotations ( io.quarkus.quarkus-resteasy
, io.quarkus.quarkus-resteasy-jackson
, version 1.13.2.Final).
我需要解析來自我調用的 API 的這種響應:
[
{
"name": "John Smith",
"age": 43
},
{
"name": "Jane Doe",
"age": 27
}
]
我無法更改此響應(例如,將此數組包裝在具有屬性的 object 中)。 響應正文的根元素是一個數組。
這是 model class:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Person {
private final String name;
private final int age;
@JsonCreator
public Person(@JsonProperty("name") String name,
@JsonProperty("age") int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
以下是我請求 API 的方式:
ResteasyClient resteasyClient = new ResteasyClientBuilderImpl().build();
try {
Response response = resteasyClient.target("/api/path")
.queryParam("param1", "value1")
.request()
.get();
List<Perso> person = response.readEntity( /* ? */ );
}
catch (ProcessingException e) {
// Handle the error...
}
我不能在 readEntity 方法中使用List<Person>.class
readEntity
"Cannot select from parameterized type"
)。
我嘗試創建一個包含列表的Persons
包裝器 object。 但是 JSON 內容不是具有列表屬性的 object ,它是一個數組。 所以它不起作用。
readEntity
方法有一個變體,它采用GenericType
而不是Class
。 您可以使用readEntity(new GenericType<List<Person>>() {})
。
如果您有興趣, GenericType
class 使用了一個聰明的技巧,據我所知,Neal Gafter 在他的 Super Type Tokens 文章中首次描述了該技巧: http://gafter.blogspot.com/2006/12/超級類型令牌。html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.