简体   繁体   English

使用 Resteasy 和 Jackson 注释从响应正文中解析 JSON 数组

[英]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). I'm using Resteasy with Quarkus, and Jackson annotations ( io.quarkus.quarkus-resteasy , io.quarkus.quarkus-resteasy-jackson , version 1.13.2.Final).

I need to parse this kind of response from an API I call:我需要解析来自我调用的 API 的这种响应:

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

I can't change this response (wrap this array inside an object with a property, for example).我无法更改此响应(例如,将此数组包装在具有属性的 object 中)。 The root element of the response body is an array.响应正文的根元素是一个数组。

Here is the model class:这是 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;
    }
}

And here is how I request the API:以下是我请求 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...
}

I can't use List<Person>.class in the readEntity method ( "Cannot select from parameterized type" ).我不能在 readEntity 方法中使用List<Person>.class readEntity "Cannot select from parameterized type" )。

I tried creating a Persons wrapper object which contains the list.我尝试创建一个包含列表的Persons包装器 object。 But the JSON content in not an object with a list property, it is an array.但是 JSON 内容不是具有列表属性的 object ,它是一个数组。 So it doesn't work.所以它不起作用。

The readEntity method has a variant that, instead of a Class , takes a GenericType . readEntity方法有一个变体,它采用GenericType而不是Class You can use readEntity(new GenericType<List<Person>>() {}) .您可以使用readEntity(new GenericType<List<Person>>() {})

In case you're interested, the GenericType class uses a clever trick that, to the best of my knowledge, was first described by Neal Gafter in his Super Type Tokens article: http://gafter.blogspot.com/2006/12/super-type-tokens.html如果您有兴趣, GenericType class 使用了一个聪明的技巧,据我所知,Neal Gafter 在他的 Super Type Tokens 文章中首次描述了该技巧: http://gafter.blogspot.com/2006/12/超级类型令牌。html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM