我试图了解空 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/