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

解析JSON数组触发空指针异常:Iterator.hasNext()调用失败排查

问题根源与修复方案:JSON数组遍历空指针异常

核心错误出在DTO类定义,和遍历方式无关

  1. InvoicesDTO类逻辑完全错误
    你让InvoicesDTO实现了List<InvoicesDTO>,这完全不符合逻辑——单个发票对象不需要继承List接口。Jackson反序列化JSON数组时,会因为这个错误的类定义无法正确解析数据,最终导致invoiceDTO.getInvoices()返回null,遍历触发空指针异常。

  2. InvoiceDTO字段类型不匹配JSON结构
    JSON里的invoices是数组,但你在InvoiceDTO里把它定义成了单个InvoicesDTO对象,类型不匹配会导致Jackson无法正确映射数据,字段值直接为null。


修正后的DTO类

1. 正确的InvoicesDTO(移除List实现)

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class InvoicesDTO {
    @NotNull(message = "invoice Number can't be null")
    private String invoiceNumber;

    @NotNull(message = "invoiceAmount can't be null")
    private Double invoiceAmount; 
}

2. 修正后的InvoiceDTO(字段改为List类型)

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class InvoiceDTO {
    @NotNull(message = "PersonId can't be null")
    @PersonId
    private String personId;

    @NotNull(message = "invoiceDate can't be null")
    @PastOrPresent
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate invoiceDate;

    // 改为List<InvoicesDTO>,对应JSON中的数组结构
    private List<InvoicesDTO> invoices;
}

业务代码优化(可选)

遍历前增加空判断,避免后续再出现类似空指针问题:

try {
    Optional<Debts> debts = debtsRepository.findDebtsByPersonIdAndOrganization_id(invoiceDTO.getPersonId(), organization.get().getId());
    Optional<Madeen> madeenOptional = madeenRepository.findByPersonId(invoiceDTO.getPersonId());

    List<InvoicesDTO> invoicesDTO = invoiceDTO.getInvoices();
    // 先判空再遍历
    if (invoicesDTO != null && !invoicesDTO.isEmpty()) {
        for (InvoicesDTO invoice : invoicesDTO) {
            Debts newDebt = new Debts();
            newDebt.setPersonId(invoiceDTO.getPersonId());
            newDebt.setCreatedDate(LocalDate.now());
            newDebt.setUpdatedDate(invoiceDTO.getInvoiceDate());
            newDebt.setDebtAmount(invoice.getInvoiceAmount());
            newDebt.setInvoiceNumber(invoice.getInvoiceNumber());
            newDebt.setOrganization(organization.get());
            debtsRepository.save(newDebt);
        }
    }
}
// 记得补全catch块

内容的提问来源于stack exchange,提问作者TechNewPy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:05:32