无法反序列化java.util.ArrayList`

时间:2019-05-03 16:55:06

标签: java php json spring-boot

我在尝试从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}\"}"; 
    }

这是我的Java代码,用于从JSON文件获取数据。

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 test

谢谢您

1 个答案:

答案 0 :(得分: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();