【问题标题】:Parse JSON array from a response body using Resteasy and Jackson annotations使用 Resteasy 和 Jackson 注释从响应正文中解析 JSON 数组
【发布时间】:2021-05-14 11:31:50
【问题描述】:

我正在使用带有 Quarkus 和 Jackson 注释的 Resteasy(io.quarkus.quarkus-resteasyio.quarkus.quarkus-resteasy-jackson,版本 1.13.2.Final)。

我需要从我调用的 API 解析这种响应:

[
  {
    "name": "John Smith",
    "age": 43
  },
  {
    "name": "Jane Doe",
    "age": 27
  }
]

我无法更改此响应(例如,将此数组包装在具有属性的对象中)。响应体的根元素是一个数组。

这是模型类:

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&lt;Person&gt;.class ("Cannot select from parameterized type")。

我尝试创建一个包含列表的Persons 包装器对象。但是 JSON 中的内容不是具有列表属性的对象,它是一个数组。所以它不起作用。

【问题讨论】:

    标签: java resteasy quarkus jackson2


    【解决方案1】:

    readEntity 方法有一个变体,它采用GenericType,而不是Class。你可以使用readEntity(new GenericType&lt;List&lt;Person&gt;&gt;() {})

    如果您有兴趣,GenericType 类使用了一个聪明的技巧,据我所知,Neal Gafter 在他的 Super Type Tokens 文章中首次描述了这个技巧:http://gafter.blogspot.com/2006/12/super-type-tokens.html

    【讨论】:

    • 我刚刚得出了同样的结论 :D 对于那些感兴趣的人,new GenericType&lt;List&lt;Person&gt;&gt;() {} 语法是一个匿名子类。您匿名声明GenericType 的子类,类型为List&lt;Person&gt;,同时实例化它。见docs.oracle.com/javase/tutorial/java/javaOO/…
    猜你喜欢
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多