解析JSON数组触发空指针异常:Iterator.hasNext()调用失败排查
问题根源与修复方案:JSON数组遍历空指针异常
核心错误出在DTO类定义,和遍历方式无关
InvoicesDTO类逻辑完全错误
你让InvoicesDTO实现了List<InvoicesDTO>,这完全不符合逻辑——单个发票对象不需要继承List接口。Jackson反序列化JSON数组时,会因为这个错误的类定义无法正确解析数据,最终导致invoiceDTO.getInvoices()返回null,遍历触发空指针异常。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
相关产品推荐
相关产品推荐

