有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java spring。杰克逊。序列化。failonemptybeans

我正试图从doc了解什么时候空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(没有getter):

@Component
public class Wrapper2 {

    private String name;

}

我要序列化的包装器类:

@Component
public class Wrapper {

        @Autowired
        private Wrapper2 wrapper2;


}

控制员:

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

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

然而,即使添加/删除了wrapper2的getter和setter,我也总是能序列化包装器。有人能解释什么时候会发生错误吗


共 (1) 个答案

  1. # 1 楼答案

    你需要你的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;
    }