Search code examples
javajsonjacksonjackson-modules

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


I'm trying to deserialize a byte array into a java type using jackson object mapper.

    @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;
       }

and using the jackson method,

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

As i am not sure what object the byte array contains, i want to it to fail when it cannot create an object of the specified type. However, objectMapper returns an object with all fields initialized to null. How do i avoid this behavior?

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}

and this is ow i have configured the 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();
    }

Solution

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

    Fields in input object that match target class will not be set to null. Therefore, make sure that there are some matching fields (fields with same name).

    If you do not want null, you may have default values for those fields. This may be done

    • at field declaration String s="default value";
    • in default, parameterless constructor. Jackson will invoke this constructor, then set values for matching fields from JSON data.

    If your source json is totally different, not single matching field then you will get object where every field is null.