RestTemplate调用外部API遇null值触发JsonMappingException问题求助
解决RestTemplate调用API时null字段导致的JsonMappingException问题
问题原因
你混用了net.sf.json.JSONObject和Jackson的ObjectMapper。当接口返回footer: null时,net.sf.json会把这个null转换成JSONNull实例,而Jackson序列化这个实例时,会尝试访问它的empty属性(该属性本身为null),最终触发JsonMappingException。
具体解决方案
方案1:统一使用Jackson的ObjectNode处理JSON
放弃net.sf.json的JSONObject,改用Jackson原生的ObjectNode接收和处理接口返回值,从根源避免库冲突:
// 修改qontakService.getDetailTemplate()方法,让它返回ObjectNode ObjectNode res2 = qontakService.getDetailTemplate(); // 后续组装结果也用Jackson的API ObjectNode gabunganResult = objectMapper.createObjectNode(); gabunganResult.put("template", objectMapper.writeValueAsString(getDetail.get())); gabunganResult.set("templateQontak", res2);
方案2:手动替换JSONObject中的JSONNull为null
如果暂时无法替换net.sf.json,可以递归遍历JSONObject,把所有JSONNull实例替换成Java原生的null:
// 递归处理JSON对象,替换所有JSONNull为null private void replaceJSONNull(JSONObject jsonObj) { Iterator<String> keyIterator = jsonObj.keys(); while (keyIterator.hasNext()) { String key = keyIterator.next(); Object value = jsonObj.get(key); if (value instanceof JSONNull) { jsonObj.put(key, null); } else if (value instanceof JSONObject) { replaceJSONNull((JSONObject) value); } else if (value instanceof JSONArray) { JSONArray jsonArray = (JSONArray) value; for (int i = 0; i < jsonArray.size(); i++) { Object arrItem = jsonArray.get(i); if (arrItem instanceof JSONObject) { replaceJSONNull((JSONObject) arrItem); } else if (arrItem instanceof JSONNull) { jsonArray.set(i, null); } } } } } // 使用时先处理res2,再组装结果 replaceJSONNull(res2); JSONObject gabunganResult = new JSONObject(); gabunganResult.put("template", objectMapper.writeValueAsString(getDetail.get())); gabunganResult.put("templateQontak", res2);
方案3:配置Jackson序列化JSONNull为null
通过自定义Jackson序列化器,让它遇到JSONNull时直接输出null,而不是尝试访问其属性:
// 创建自定义序列化器 SimpleModule jsonNullModule = new SimpleModule(); jsonNullModule.addSerializer(JSONNull.class, new JsonSerializer<JSONNull>() { @Override public void serialize(JSONNull jsonNull, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeNull(); } }); // 注册到你的ObjectMapper实例 objectMapper.registerModule(jsonNullModule);
内容的提问来源于stack exchange,提问作者Adam Abdullah
相关产品推荐
相关产品推荐

