Jackson Object Mapper 读取值(以字节为单位)返回一个所有字段都初始化为 null 的对象

Jackson Object Mapper readvalue in bytes returning a object with all fields initialized to null

我正在尝试使用 jackson 对象映射器将字节数组反序列化为 java 类型。

    @JsonIgnoreProperties(ignoreUnknown = true)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public class A {
     String s;
     String b;
    }

   @JsonIgnoreProperties(ignoreUnknown = true)
   @JsonInclude(JsonInclude.Include.NON_NULL)   
   public class B {
     String c;
     String b;
   }

      @JsonIgnoreProperties(ignoreUnknown = true)
       @JsonInclude(JsonInclude.Include.NON_NULL)   
       public class C {
         List<CustomType> x;
       }

并使用杰克逊方法,

objectMapper.readValue(byte[] data, Class<T> type).

因为我不确定字节数组包含什么对象,所以我希望它在无法创建指定类型的对象时失败。但是,objectMapper returns 一个 对象,所有字段都初始化为 null。我该如何避免这种行为?

Ex: 
byte[] b; //contains Class B data
byte[] a; //contains Class A data
byte[] c// contains Class C data
A a = objectMapper.readValue(c, A.class) is returning 
{s=null, b = null}

这就是我配置 ObjectMapper 的方式,

@Bean
    public ObjectMapper objectMapper(HandlerInstantiator handlerInstantiator) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.handlerInstantiator(handlerInstantiator);
        builder.failOnEmptyBeans(false);
        builder.failOnUnknownProperties(false);
        builder.simpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        builder.timeZone("UTC");
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);

        return builder.build();
    }

@JsonIgnoreProperties(ignoreUnknown = true) 表示您忽略未知属性。因此,如果您将 B 数据解组为 A 实例,则 c 属性 将被忽略,只是未填充,所以这就是您得到 null.[=17 的原因=]

删除此注释,您应该开始获得 JsonMappingException 或类似的注释。

@JsonInclude(JsonInclude.Include.NON_NULL)只是为了序列化。

objectMapper returns an object with all fields initialized to null. How do i avoid this behavior?

输入对象中与目标 class 匹配的字段不会设置为空。 因此,请确保有一些匹配字段(同名字段)。

如果您不想为空,您可以为这些字段设置默认值。 这可以做到

  • 在字段声明处String s="default value"
  • 默认情况下,无参数构造函数。 Jackson 将调用此构造函数,然后为来自 JSON 数据的匹配字段设置值。

如果您的源 json 完全不同,而不是单个匹配字段,那么您将得到每个字段都为空的对象。