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();
}
@JsonIgnoreProperties(ignoreUnknown = true)
says you ignore unknown properties. So if you unmarshal B
data as A
instance, the c
property is ignored, just not filled so this is why you get null
.
Remove this annotation an you should start getting JsonMappingException
or similar.
@JsonInclude(JsonInclude.Include.NON_NULL)
is just for serialization.
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
String s="default value"
; If your source json is totally different, not single matching field then you will get object where every field is null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With