WebClient:如何将JSON响应映射到对象的Flux?

问题描述

我正在尝试使用WebClient使用JSON API响应。 该API为https://www.forbes.com/forbesapi/org/global2000/2020/position/true.json?limit=2000

如您所见,响应的格式并不简单:

{
    "organizationList": {
        "count": 2000,"organizationsLists": [
            {
                "name": "Global 2000","year": 2020,"month": 5,"uri": "icbc",...
                ...
                ...
            },...
            ...
            ...
        ]
}

我要实现的目的是解析对以下类的List的响应,而不必创建其他包装类(例如OrganizationResponse,OrganizationList等):

@Data
@Document
@AllArgsConstructor
@NoArgsConstructor
public class ForbesOrganization {

    @Id
    private BigInteger id;

    private Integer rank;
    private Integer position;

    private Integer year;
    private Integer month;

    private String organizationName;
    private String description;
    private Integer yearFounded;

    private String industry;
    private String webSite;

    private boolean imageExists;
    private String image;

    private String country;
    private String state;
    private String city;

    private float revenue;
    private float profits;
    private float assets;
    private float marketValue;
}

我按如下方式创建了WebClient

public static final int MB10 = 10 * 1024 * 1024;

public static final WebClient WEB_CLIENT = WebClient.builder()
        .baseUrl("https://www.forbes.com/forbesapi")
        .defaultHeader(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_STREAM_JSON_VALUE)
        .codecs(clientCodecConfigurer -> clientCodecConfigurer.defaultCodecs()
                .maxInMemorySize(MB10))
        .build();

并希望通过以下方式调用它:

public Flux<ForbesOrganization> getGlobal2000(Integer year) {
    final String URI = String.format("/org/global2000/%d/position/true.json",year);

    return WEB_CLIENT.get()
            .uri(builder -> builder
                    .path(URI)
                    .queryParam("limit",2000)
                    .build())
            .retrieve()
            .bodyToFlux(ForbesOrganization.class);
}

但是,当我订阅时,没有得到ForbesOrganization类型的对象。 唯一的方法是创建所有需要的包装器类。

是否有任何方法可以如上所述仅获取所需对象的流量? 谢谢

更新

我在How to get a json field by name using Spring WebClient?尝试了该示例 但它在使用mapper.readValue时给我有关阻塞方法调用的警告。有替代方法吗?一个非阻塞的JSON映射器?

Blocking method warning

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)