I need to deserialize JsonArray to a boolean value. If an array exists and is not empty the value should be set to "true". The problem is, my custom deserializer, while functional, breaks deserialization of the rest of the fields - they are being set to null.
Object:
private static class TestObject {
private String name;
@JsonProperty("arr")
@JsonDeserialize(using = Deserializer.class)
private Boolean exists = null;
private Integer logins;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getExists() {
return exists;
}
public void setExists(boolean exists) {
this.exists = exists;
}
public Integer getLogins() {
return logins;
}
public void setLogins(Integer logins) {
this.logins = logins;
}
@Override
public String toString() {
return "TestObject{" +
"name='" + name + '\'' +
", exists=" + exists +
", logins=" + logins +
'}';
}
}
Deserializer:
public class Deserializer extends JsonDeserializer<Boolean> {
@Override
public Boolean deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException {
if (jp.getCurrentToken() == JsonToken.START_ARRAY) {
return true;
}
return false;
}
}
Test
@Test
public void test() throws JsonParseException, IOException {
Boolean result = deserialize();
}
private Boolean deserialize() throws IOException, JsonParseException,
JsonProcessingException {
TestObject testObject = mapper.readValue("{\n" +
" \"arr\": [\n" +
" {\"value\": \"New\"}\n" +
" ],\n" +
" \"name\": \"name\",\n" +
" \"logins\": 36" +
"}",
TestObject.class);
System.out.println(testObject.toString());
return testObject.getExists();
}
If i remove the "arr" array or move it to the bottom of the Json, everything's fine. If i leave it at the top - TestObject{name='null', exists=true, logins=null}
.
There was a similar question (Jackson Custom Deserializer breaks default ones), but unfortunately it has zero answers. Since the code works properly when i rearrange Json, it doesn't look like custom deserializer is used for all fields, rather Jackson stops deserialization when it executes custom deserializer.
getExists
returnarr != null
or some such. – Paul