jackson序列化报 Null key for a Map not allowed in JSON (use a converting NullKeySerializer?)

发布时间 2023-04-07 10:20:28作者: cherrymint
    报错:"requestParam":null,"errorMsg":"org.springframework.http.converter.HttpMessageNotWritableException: 
Could not write JSON: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?); 
nested exception is com.fasterxml.jackson.databind.JsonMappingException: 
Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) 


long startTime = System.currentTimeMillis();
        Map<Long, ResultDTO> result = new HashMap<>();
        List<Future<Map<Long, ResultDTO>>> tasks = new ArrayList<>();
        TaskExecutor taskExecutor = (TaskExecutor) this.executor;
        IdentifyDTOList.forEach(IdentifyDTO ->
                tasks.add(taskExecutor.submit(() -> {
                    ResultDTO ResultDTO = new ResultDTO();
                    Map<Long, ResultDTO> map = new HashMap<>();
                    try {
                        ResultDTO = Service.this.multiple(IdentifyDTO);
                    } catch (Exception e) {
                        log.error("接口返回错误信息:{}", e);
                        ResponseDTO status = new ResponseDTO();
                        status.setResultCode(e.getCode());
                        status.setMessage(e.getMessage());
                        ResultDTO.setStatus(status);
                    } catch (Exception e) {
                        log.error("接口识别报错:{}", e);
                    }
                    map.put(IdentifyDTO.getAttachmentId(), ResultDTO);
                    return map;
                })));

        tasks.forEach(ft -> {
            try {
                result.putAll(ft.get());
            } catch (Exception e) {
                log.error("接口线程处理失败:{}", e);
            }
        });
        log.info("处理时间: " + (System.currentTimeMillis() - startTime) + "ms");
        return result;



此处 map.put(IdentifyDTO.getAttachmentId(), ResultDTO);
result接收map中key值为null,报该异常;解决方法:在传入的key值中赋给相关的值使其不为null或者改造key的赋值逻辑即可。