You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

学习API开发:文件列表接口返回含null字段的JSON问题

解决API返回JSON字段全为null、size为0的问题

核心问题1:ResponseFile构造函数未正确赋值

你的ResponseFile构造函数犯了低级错误——把成员变量赋值给自身,完全没用到传入的参数。比如this.nome = nome里的nome是类的成员变量(默认null),不是构造函数的参数nomeArquivo,导致所有字段都保持初始值。

错误的构造函数:

public ResponseFile(String nomeArquivo, String fileDownloadUri, String tipoExame, int length) {
    this.nome = nome;
    this.url = url;
    this.type = type;
    this.size = size;
}

修复后的构造函数(补充患者、医生字段的参数):

public ResponseFile(String nomeArquivo, String fileDownloadUri, String tipoExame, long length, Paciente paciente, Medico medico) {
    this.nome = nomeArquivo;
    this.url = fileDownloadUri;
    this.type = tipoExame;
    this.size = length;
    this.paciente = paciente;
    this.medico = medico;
}

核心问题2:未填充Paciente和Medico字段

你的ResponseFile包含paciente和medico字段,但原代码创建对象时没有传入这些数据。需要从dbFile中获取关联的患者、医生信息,在map阶段传入构造函数:

修改后的endpoint代码:

@GetMapping("/files")
public ResponseEntity<List<ResponseFile>> getListFiles() {
    List<ResponseFile> files = resultadosExamesService.listarTodosArquivos().map(dbFile -> {
        String fileDownloadUri = ServletUriComponentsBuilder
                .fromCurrentContextPath()
                .path("/exames/files/")
                .path(dbFile.getIdExame().toString())
                .toUriString();

        // 从dbFile获取关联的患者、医生数据(假设dbFile有对应的getter方法)
        Paciente paciente = dbFile.getPaciente();
        Medico medico = dbFile.getMedico();

        return new ResponseFile(
                dbFile.getNomeArquivo(),
                fileDownloadUri,
                dbFile.getTipoExame(),
                dbFile.getArquivoExame().length,
                paciente,
                medico);
    }).collect(Collectors.toList());

    return ResponseEntity.status(HttpStatus.OK).body(files);
}

额外验证步骤

  1. 确认resultadosExamesService.listarTodosArquivos()返回的dbFile对象本身字段有效:比如dbFile.getNomeArquivo()、dbFile.getTipoExame()、dbFile.getArquivoExame()这些方法是否真的能从数据库拿到非null数据。如果Service层查询出来的数据就是null,上层处理也没用。
  2. 检查实体类的Getter/Setter是否正确:确保nome、url等字段的Getter方法命名规范(比如getNome()),JSON序列化框架(如Jackson)依赖正确的Getter来生成字段。

内容的提问来源于stack exchange,提问作者Víctor Monteiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 23:50:24