【问题标题】:Entire large json response is not returned不返回整个大的 json 响应
【发布时间】:2021-12-16 13:28:45
【问题描述】:

我正在尝试使用如下递归 REST 调用来获得大型 json 响应:

private List<MyPojo> recursiveRestCallMethod(String folderId) throws IOException {
    
    List<MyPojo> mypojoList = new ArrayList<>();
    
    String hugeJson = webClient.get()
            .uri("/my/rest/api/accepting/" + folderId
                    + "/and/producing/huge/jsonresponse/for/all/files/recursively")
            .retrieve().bodyToMono(String.class).block();
    
    byte[] bytes = hugeJson.getBytes("UTF-8");
    
    String json = new String(bytes, StandardCharsets.UTF_8);
    
    ObjectMapper objectMapper = new ObjectMapper();
    
    ObjectNode node = objectMapper.readValue(json, ObjectNode.class);
    
    objectMapper.configure(
            DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    
    if (node.get("list").get("entries").isArray()) {
        for (JsonNode jsonNode : node.get("list").get("entries")) {
            
            MyPojo pojo = new MyPojo();
            
            JsonNode mainNode = jsonNode.get("entry");
            
            if (mainNode.get("isFile").asBoolean()) {
                JsonNode nameNode = mainNode.get("name");
                pojo.setNodename(nameNode.toString());
                // and 20 more fields
                mypojoList.add(pojo);
            }
            if (mainNode.get("isFolder").asBoolean()) {
                mypojoList.addAll(recursiveRestCallMethod(mainNode.get("id").toString().replaceAll("\"", "").trim()));
            }
            
        }
        return mypojoList;
    }
    return null;
}

现在每次返回的 json 有 4193150 个字符并抛出异常 - Unexpected end-of-input: expected close marker for Object 报告为 here 和其他一些 SO 线程(显然,json 不完整且有效)。

我得到的不完整的 json 看起来像:

{"list":{"pagination":{"count":6097,"hasMoreItems":false,"totalItems":6097,"skipCount":0,"maxItems":10000},"entries":[{"entry":{"....

从上面可以看出,我应该得到 6097 个对象,但我只得到 2024 个条目数组项。之后 json 突然结束。即无效的 json 字符串。

但是,对于较小的响应,我有 20/30 个条目数组项,它按预期工作。

注意:我使用的是 Spring-Boot 2.4.5,因此使用的是 Jackson 2.12.4

问题:即使我使用.block(),为什么响应停止在4193150 个字符处?我在这里做错了什么?

【问题讨论】:

  • 是否有可能是另一端的服务真的无法序列化大 JSON?鉴于问题中的特殊代码,至少可以说您正在处理一个困难的 API。
  • 例如(shivers):mainNode.get("id").toString().replaceAll("\"", "").trim()

标签: java spring-boot jackson spring-webflux


【解决方案1】:

不确定使用 String 出了什么问题,但是当我切换到 DataBuffer 时,它工作正常。

这是我使用的 sn-p:

    final Flux<DataBuffer> hugeJson = webClient.get()
            .uri("/my/rest/api/accepting/" + folderId
                    + "/and/producing/huge/jsonresponse/for/all/files/recursively")
            .accept(MediaType.ALL)
            .retrieve()
            .bodyToFlux(DataBuffer.class);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多