【问题标题】:Cannot deserialize instance of `java.util.ArrayList`无法反序列化“java.util.ArrayList”的实例
【发布时间】:2019-09-22 06:14:34
【问题描述】:

我在尝试从 JSON 文件中获取数据时遇到问题。我的 JAVA 方面正在工作,但是在组装 JSON 的 PHP 中进行了更改,因为我无法执行解析器,我不知道在 PHP 中知道我得到的 JSON 格式,但我可以访问代码。 JSON挂载的页面是这样的:

<?php
    $startTime = microtime(true);
    include_once("../utils/config.php");
    include_once("../utils/utils.php");
    include_once("../services/rest.utils.php");

    header("Content-Type: application/json",true);

    $from = getADate('from', true);
    $to = getADate('to', false);
    $fromDate = '';
    $toDate = '';
    if ($from <> '') { $fromDate = $from; }
    if ($to <> 'NULL') { $toDate = $to; }

    $body = file_get_contents('php://input');

    if (signatureCheck($body)) {
        $cta = 0;
        $database = conectaDatabase();
        $script = '';
        $pfx = Config::getPrefixo();

        $sql = "SELECT RelatorioID, ProfessorID, AlunoID, TurmaID,
                Bimestre, Data, TipoRelatorio, Conteudo, Situacao FROM {$pfx}Relatorios
                WHERE Data >= $fromDate";
        if ($toDate <> '') { 
            $sql .= " AND Data < $toDate";
        }   

        $qry = $database->query($sql);
        $lista = array();
        $cta = 0;
        while ($row = $qry->fetchObject()) {
            $row->TipoRelatorio = utf8_encode($row->TipoRelatorio);
            $row->Conteudo = utf8_encode($row->Conteudo);
            $lista[] = $row;
            $cta++;
        }

        @$output->response = new StdClass(); // Anonymous object, remove the warning
        $output->response->descricao = "$cta relatórios importados";
        $output->response->status = 200;
        $output->relatorios = $lista;

        $endTime = microtime(true);
        $timeSpent = $endTime - $startTime;
        $output->response->timeSpent = $timeSpent;

        $saida = json_encode($output, JSON_UNESCAPED_UNICODE);
        echo $saida;

        desconectaDB($database);
    } else {
        $description = "não autorizado";
        $status = "401";
        $endTime = microtime(true);
        $timeSpent = $endTime - $startTime;
        echo "{\"status\":{$status}, \"descricao\":\"$description\", \"timeSpent\": \"{$timeSpent}\"}"; 
    }

这是我从 JSON 文件中获取数据的 java 代码。

public void myGeRelatorios() {

try {
    String targetUrl = "https://develop.bedelonline.com.br/services/importa.relatorios.php?from=2019-01-03T00:00:00Z";

    HttpHeaders header = new HttpHeaders();
    header = Useful.newGetHeaderForImport();
    HttpEntity<String> entity = new HttpEntity<>("parameters", header);
    ResponseEntity<List<RelatorioResponse>> response = rt.exchange(targetUrl, HttpMethod.GET, entity, new ParameterizedTypeReference<List<RelatorioResponse>>() {});
    List<RelatorioResponse> responses = response.getBody();
    doWithResponse(responses);
} catch (Exception e) {
    LOGGER.error(e.getMessage());
}

}

我的回复类

public class RelatorioResponse {


    @JsonProperty("RelatorioID")
    private Integer RelatorioID;

    @JsonProperty("ProfessorID")
    private Integer ProfessorID;

    @JsonProperty("AlunoID")
    private Integer AlunoID;

    @JsonProperty("TurmaID")
    private Integer TurmaID;

    @JsonProperty("Bimestre")
    private Integer Bimestre;

    @JsonProperty("Data")
    private Date Data;

    @JsonProperty("TipoRelatorio")
    private String TipoRelatorio;

    @JsonProperty("Conteudo")
    private String Conteudo;

    @JsonProperty("Situacao")
    private Integer Situacao;

    public Integer getRelatorioID() {
        return RelatorioID;
    }

    public void setRelatorioID(Integer relatorioID) {
        RelatorioID = relatorioID;
    }

    public Integer getProfessorID() {
        return ProfessorID;
    }

    public void setProfessorID(Integer professorID) {
        ProfessorID = professorID;
    }

    public Integer getAlunoID() {
        return AlunoID;
    }

    public void setAlunoID(Integer alunoID) {
        AlunoID = alunoID;
    }

    public Integer getTurmaID() {
        return TurmaID;
    }

    public void setTurmaID(Integer turmaID) {
        TurmaID = turmaID;
    }

    public Integer getBimestre() {
        return Bimestre;
    }

    public void setBimestre(Integer bimestre) {
        Bimestre = bimestre;
    }

    public Date getData() {
        return Data;
    }

    public void setData(Date data) {
        Data = data;
    }

    public String getTipoRelatorio() {
        return TipoRelatorio;
    }

    public void setTipoRelatorio(String tipoRelatorio) {
        TipoRelatorio = tipoRelatorio;
    }

    public String getConteudo() {
        return Conteudo;
    }

    public void setConteudo(String conteudo) {
        Conteudo = conteudo;
    }

    public Integer getSituacao() {
        return Situacao;
    }

    public void setSituacao(Integer situacao) {
        Situacao = situacao;
    }
}

这是我尝试解析 JSON 时发生的错误

org.springframework.web.client.RestClientException: Error while extracting response for type
 [java.util.List<com.test.bws.response.RelatorioResponse>] and 
content type [application/json]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 1]


Error while extracting response for type [java.util.List<com.test.bws.response.RelatorioResponse>] and content type [application/json]

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 1]

感谢任何帮助

【问题讨论】:

  • JSON 中的响应是什么样的?要反序列化数组列表,我希望您需要一个 JSON 对象数组。至少,else 子句中返回的 JSON 看起来不符合此标准。
  • @akokskis 我插入了他们发送的测试图像

标签: java php json spring-boot


【解决方案1】:

问题是你的 JSON 看起来像这样:

{
  "response": {
    ...
  },
  "relatorios": [
    {
      ...
    }
  ]
}

您正试图将其直接映射到relatorios 列表。您应该创建另一个 RestResponse 对象。这应该包含整个 JSON 响应内容:

public class RestResponse {
    private MyResponse response;
    private List<RelatorioResponse> relatorios;
    // getter and setter
}

response 对象应代表 JSON 中的 response 部分。如果您不需要,您也可以将@JsonIgnoreProperties(ignoreUnknown = true) 添加到您的RestResponse 类并省略response 属性:

@JsonIgnoreProperties(ignoreUnknown = true)
public static class RestResponse {
    private List<RelatorioResponse> relatorios;
    // getter and setter
}

您的请求代码应如下所示:

HttpEntity<String> entity = new HttpEntity<>("parameters", new HttpHeaders());
ResponseEntity<RestResponse> response = new RestTemplate().exchange(targetUrl, HttpMethod.GET, entity, RestResponse.class);
List<RelatorioResponse> responses = response.getBody().getRelatorios();

【讨论】:

    猜你喜欢
    • 2013-01-13
    • 2021-06-09
    • 2014-01-17
    • 2017-03-02
    • 2021-03-26
    • 2017-09-22
    • 2020-02-20
    相关资源
    最近更新 更多