java - spring.jackson.serialization.fail-on-empty-beans

标签 java spring spring-boot jackson deserialization

我试图了解空 bean 失败的时间,来自文档:

public static final SerializationFeature FAIL_ON_EMPTY_BEANS Feature that determines what happens when no accessors are found for a type (and there are no annotations to indicate it is meant to be serialized). If enabled (default), an exception is thrown to indicate these as non-serializable types; if disabled, they are serialized as empty Objects, i.e. without any properties. Note that empty types that this feature has only effect on those "empty" beans that do not have any recognized annotations (like @JsonSerialize): ones that do have annotations do not result in an exception being thrown.

Feature is enabled by default.

现在我尝试创建一个空的 POJO(没有 getters):

@Component
public class Wrapper2 {

    private String name;

}

我要序列化的包装类:

@Component
public class Wrapper {

        @Autowired
        private Wrapper2 wrapper2;


}

Controller :

@RestController
public class TestController {
    @Autowired
    private Wrapper wrapper;

        @GetMapping("/test")
        public Wrapper test() {
          return wrapper;
        }
    }

但是,即使为 wrapper2 添加/删除 getter 和 setter,我也总是让包装器序列化。谁能解释错误何时会发生?

最佳答案

您需要您的 bean 并且没有可识别的注释

Note that empty types that this feature has only effect on those "empty" beans that do not have any recognized annotations

因此,如果您删除注释,它将失败

public class Wrapper {

}

错误将是

Unrecognized field "wrapper" (class com.Wrapper ), not marked as ignorable (0 known properties: ])

Jackson标记为UnknownSerializer时应用的相关代码:

if (isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)) {
        if (ser instanceof UnknownSerializer) {
            return true;

嵌套空类的类似异常:

public class Wrapper {
   private Wrapper2 wrapper2;
}

关于java - spring.jackson.serialization.fail-on-empty-beans,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53978028/

相关文章:

java - 如何初始化 spring 集成 :gateway at startup?

java - 当 ActiveMQ 故障转移传输失败时,Spring Boot 应用程序不会启动

java - Spring RedisMap初始化时返回null

java - 如何在 Android 应用程序上设置环境属性?

java - 释放 HttpClient 4.1.x 的连接以使用一个 HttpClient 实例顺序执行

java - Hibernate 和 Spring 事务——使用私有(private)构造函数/静态工厂方法

spring-security - AuthenticationException 会发生什么情况?

java - 为什么 Controller 需要在绑定(bind)错误上添加模型

java - MapStruct 实现在 Spring Boot Web 应用程序中不起作用

java - HDFS 目录中的文件数