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

调用API时JSON序列化失败:Object is null问题求助

问题:JSON序列化时因null对象抛出异常

调用数据库保存接口时,updated at、updated by等字段为空,结果返回至Controller时触发错误:Could not write JSON: Object is null,根因异常为net.sf.json.JSONException: Object is null。

完整错误栈

com.fasterxml.jackson.databind.JsonMappingException: Object is null (through reference chain: java.util.HashMap["details"]->net.sf.json.JSONObject["template"]->net.sf.json.JSONObject["createTemplate"]->net.sf.json.JSONObject["attributes"]->net.sf.json.JSONArray[0]->net.sf.json.JSONObject["components"]->net.sf.json.JSONArray[1]->net.sf.json.JSONObject["example"]->net.sf.json.JSONNull["empty"])

相关Controller代码

@PostMapping(value = "/saving",produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> save(
    @RequestHeader(value = "apps") String apps,
    @RequestHeader(value = "module") String module,
    @Valid @RequestBody CreateTemplate requestData) throws IOException, InterruptedException, URISyntaxException, ApiResponseThrow 
{
    
    log.info("START saveTemplateQontak function");
    Map<String, Object> result = new HashMap<>();
    
    String jwt = AuthTokenFilter.parseJwt(request);
    String username = jwtUtils.getUserNameFromJwtToken(jwt);

    LogFormat logFormat = new LogFormat();
    logFormat.setAction("saving");
    logFormat.setApps(apps);
    logFormat.setModule(module);
    logFormat.setUser(username);
    log.info("DATA BEFORE == {}", objectMapper.writeValueAsString(requestData));
    log.info("log-format == {}", logFormat);
    
    // JSONObject token = qontakService.getTokenQontak();
    // JSONObject res = qontakService.saveTemplateToQontak(objectMapper.writeValueAsString(requestData), token.get("access_token").toString());
    // requestData.getAttributes().get(0).getComponents().get(0).getType()
    JSONObject res = templateService.saveHeaderTemplate(requestData, logFormat);
    log.info("END templateService.save() CREATE");

    result.put("httpCode", HttpStatus.OK);
    result.put("status", "00");
    result.put("message", "Success Saving");
    result.put("details",res);

    log.info("END save function");

    return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
}

解决方案

1. 配置Jackson忽略null字段

Spring默认使用Jackson序列化JSON,可全局配置忽略null值,避免因null字段触发异常:

  • 通过application.yml配置:
spring:
  jackson:
    default-property-inclusion: non_null
  • 或者通过配置类自定义ObjectMapper:
@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 序列化时忽略null字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return objectMapper;
    }
}

2. 修复Service层返回的JSONObject

错误栈显示example字段对应net.sf.json.JSONNull,导致Jackson无法正常序列化。在Service层构建JSONObject时,过滤掉null值或替换JSONNull:

// 示例:构建components的JSONObject时处理null值
if (component.getExample() == null) {
    jsonObject.remove("example"); // 移除null字段
} else {
    jsonObject.put("example", component.getExample());
}

3. 统一JSON处理库,避免混用

当前代码混用了net.sf.json和Jackson,两者兼容性不佳。建议统一使用Jackson的ObjectNode替代net.sf.json.JSONObject,或者将现有JSONObject转为Jackson可处理的结构:

// 将net.sf.json.JSONObject转为Jackson的ObjectNode
ObjectMapper mapper = new ObjectMapper();
ObjectNode jacksonNode = mapper.readValue(res.toString(), ObjectNode.class);
result.put("details", jacksonNode);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:55:15