Jackson ignoring specific property but able to check was it availble

micobg :

Is there a way to skip some properties on deserialization but at the same time knowing are they presented or not?

{
    "id": 123,
    "name": "My Name",
    "picture": {
        // a lot of properties that's not important for me
    }
}
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
    private int id;
}

So, I ignoreUnknown is what I want as a default behavior because I don't want name field and all other fields that can exist. The value of picture fields also is not important. I just want to know was picture property available or not. How I can do that?

Michał Ziober :

You can add a boolean property and custom deserializer which just reads given value and returns true. Jackson invokes custom deserializer only if property exists in payload.

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.io.File;
import java.io.IOException;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./src/main/resources/test.json");
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue(jsonFile, User.class));
    }
}

class PropertyExistsJsonDeserializer extends JsonDeserializer<Boolean> {
    @Override
    public Boolean deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        p.readValueAsTree(); //consume value
        return Boolean.TRUE;
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
class User {
    private int id;

    @JsonDeserialize(using = PropertyExistsJsonDeserializer.class)
    @JsonProperty("picture")
    private boolean pictureAvailable;

    //getters, setters, toString
}

Above code prints:

User{id=123, pictureAvailable=true}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=359429&siteId=1