Jackson 包含 non_null 不能处理来自 kotlin 扩展函数的对象

Posted

技术标签:

【中文标题】Jackson 包含 non_null 不能处理来自 kotlin 扩展函数的对象【英文标题】:Jackson include non_null not working on object from kotlin extension function 【发布时间】:2020-08-18 17:32:14 【问题描述】:

我有一个spring boot项目

我在 application.properties 中设置了全局 spring.jackson.default-property-inclusion: non_null,这将删除除对象列表之外的所有空值。

另外,尝试在类级别添加 @JsonInclude ,如下所示

@JsonInclude(JsonInclude.Include.NON_NULL) 
class ClassData  

 String classId;

 List<Students> students = new ArrayList<>();



@JsonInclude(JsonInclude.Include.NON_NULL)

class Students 
studentId,
isVerified,
studentType


来自我的服务器的响应 - 它仍然包含空值,但在列表结构之外,空值正在被删除


  "students": [
    
      "studentId": null,
      "isVerified": true,
      "studentType": null
    ,
      "studentId": null,
      "isVerified": true,
      "studentType": null
    ,
      "studentId": null,
      "isVerified": true,
      "studentType": null
    ,
      "studentId": null,
      "isVerified": true,
      "studentType": null
    ,
      "studentId": null,
      "isVerified": true,
      "studentType": null
    
  ]

这是我在 kotlin 中的转换方法,它将 StudentDetail 从另一个服务转换为内部 Student 对象

fun StudentDetail.toStudent(): Student 
    return Student().apply 
        transactionId = transactionId
        isVerified = isVerified
        transactionType = transactionType
    

Spring boot 版本 - 2.2.6.RELEASE

其余所有对象都工作正常,除 ClassData 之外的空值被删除?将不胜感激任何帮助

【问题讨论】:

你如何回报这个共鸣?您的错误不可重现.. 您使用哪个 spring-boot 版本? spring boot 版本是 2.2.6.RELEASE。 ,将响应返回为 ResponseEntity.ok(someClass.getResponse())? 【参考方案1】:

对象是根据 openapi 规范生成的,其中 studentId 和 studentType 是根据需要设置的。因此,他们来响应。修复它们。

【讨论】:

以上是关于Jackson 包含 non_null 不能处理来自 kotlin 扩展函数的对象的主要内容,如果未能解决你的问题,请参考以下文章

即使使用 NON_NULL,Jackson ObjectMapper 也会抛出 NullPointerException

jackson 处理空值

@JsonInclude(Include.NON_NULL)

java jackson全局设置LocalDateTime的格式

java jackson全局设置LocalDateTime的格式

java jackson全局设置LocalDateTime的格式