【发布时间】:2017-11-19 01:07:30
【问题描述】:
当我调用返回具有空字符串属性的对象的 Web 服务时,我的 Spring 项目出现问题。
在我的项目中,我有 Spring boot 1.5.2、Spring 4.3.7 和 Jackson 2.8.7。
我使用 RestTemplate 来调用网络服务。
ResponseEntity<T> responseEntity = restTemplate.exchange("web-service-HttpMethod.GET, null, MyObject.Class);
return responseEntity.getBody();
如果我在浏览器中调用网络服务,它会返回这个响应:
{
"display_item_code": "NEP054",
"historic": false,
"popin_type_code": "",
"combo_box": false,
"max_combo_box_elements": 0,
"data_max_length": 0,
"data_precision": 0,
"data_min_length": 0,
"data_control_type_code": "",
"data_control_value1": "",
"data_control_value2": "",
"data_format": "MAJUS",
"translatable": false,
"translation_key_type_code": "",
"default_value_setting": "",
"default_value": "",
"text_area": false,
"family_code": "",
"popin": null,
"combo_values": null
}
这是预期的结果。 但是当我在我的应用程序中调用这个网络服务时,我得到了这个对象:
{
"display_item_code": "NEP054",
"historic": false,
"popin_type_code": null,
"combo_box": false,
"max_combo_box_elements": 0,
"data_max_length": 0,
"data_precision": 0,
"data_min_length": 0,
"data_control_type_code": null,
"data_control_value1": null,
"data_control_value2": null,
"data_format": "MAJUS",
"translatable": false,
"translation_key_type_code": null,
"default_value_setting": null,
"default_value": null,
"text_area": false,
"family_code": null,
"popin": null,
"combo_values": null
}
所有具有空值的属性现在都为空。 我认为需要配置一些东西,可能是 ObjectMapper 或 JsonParser,但我不知道该怎么做。 目前我使用默认的 Serializer、ObjectMapper 和 JsonParser。 我让 Spring Boot 进行自动配置。
如何配置我的应用程序在反序列化对象时保留空字符串?
编辑:我尝试this solution 通过向 ObjectMapper 添加一个模块以进行字符串反序列化,但从未调用此方法。
编辑 2:在 BeanDeserializer 类中,在反序列化期间,字段“popin_type_code”的 JsonToken 等于 JsonToken.VALUE_NULL。 我不明白 Spring/Jackson 是如何生成这个 JsonToken 的。
【问题讨论】:
-
我刚刚尝试了这个解决方案,但它并没有解决我的问题。
-
我希望你把它换成相反的,因为你想要反之亦然。
-
当然换反了。