Home > Software engineering >  Jackson searches method on wrong level on deserialization
Jackson searches method on wrong level on deserialization

Time:11-16

I am trying to read a JSON into the class. Jackson wants to apply a field of a subelement to the element itself, where it of course does not exist.

This is the JSON:

{
        "authorizationRequest":{
                "scope":["write","read"],
                "resourceIds":["metadata"],
                "approved":true,
                "authorities":[],
                "authorizationParameters":{
                        "scope":"write read",
                        "response_type":"token",
                        "redirect_uri":"",
                        "state":"",
                        "stateful":"false",
                        "client_id":"5102686_metadata"
                },
                "approvalParameters":{},
                "state":"",
                "clientId":"5102686_metadata",
                "redirectUri":"",
                "responseTypes":["token"],
                "denied":false
        },
        "credentials":"",
        "clientOnly":false,
        "name":"testuser"
}

The classes look like the following:

// The main class that I try do deserialize:
public class DeserializedOAuth2Authentication extends OAuth2Authentication{

    private String name;

    private boolean clientOnly;

    private AuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest("", new ArrayList<>());

    public DeserializedOAuth2Authentication() {
        super(new DefaultAuthorizationRequest("", new ArrayList<>()), null);
    }

    @Override
    @JsonProperty
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    @JsonProperty
    public boolean isClientOnly() {
        return clientOnly;
    }

    public void setClientOnly(boolean clientOnly) {
        this.clientOnly = clientOnly;
    }

    @Override
    @JsonProperty
    public AuthorizationRequest getAuthorizationRequest() {
        return authorizationRequest;
    }

    public void setAuthorizationRequest(AuthorizationRequest authorizationRequest) {
        this.authorizationRequest = authorizationRequest;
    }

}

AuthorizationRequest is an interface with all the getters for the listed elements; it is configured to be serialized by a DefaultAuthorizationRequest class also containing the respective setters and implementing fileds with corresponding names.

public class DefaultAuthorizationRequest implements AuthorizationRequest, Serializable {

    private Set<String> scope = new LinkedHashSet<String>();

    private Set<String> resourceIds = new HashSet<String>();

    private boolean approved = false;

    private Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

    private Map<String, String> authorizationParameters = new ConcurrentHashMap<String, String>();

    private Map<String, String> approvalParameters = new HashMap<String, String>();

    private String resolvedRedirectUri;

    public Map<String, String> getAuthorizationParameters() {
        return Collections.unmodifiableMap(authorizationParameters);
    }

    public Map<String, String> getApprovalParameters() {
        return Collections.unmodifiableMap(approvalParameters);
    }

    public String getClientId() {
        return authorizationParameters.get(CLIENT_ID);
    }

    public Set<String> getScope() {
        return Collections.unmodifiableSet(this.scope);
    }

    public Set<String> getResourceIds() {
        return Collections.unmodifiableSet(resourceIds);
    }

    public Collection<GrantedAuthority> getAuthorities() {
        return Collections.unmodifiableSet((Set<? extends GrantedAuthority>) authorities);
    }

    public boolean isApproved() {
        return approved;
    }

    public boolean isDenied() {
        return !approved;
    }

    public String getState() {
        return authorizationParameters.get(STATE);
    }

    public String getRedirectUri() {
        return resolvedRedirectUri == null ? authorizationParameters.get(REDIRECT_URI) : resolvedRedirectUri;
    }

    public Set<String> getResponseTypes() {
        return OAuth2Utils.parseParameterList(authorizationParameters.get(RESPONSE_TYPE));
    }

    public void setRedirectUri(String redirectUri) {
        this.resolvedRedirectUri = redirectUri;
    }

    public void setScope(Set<String> scope) {
        this.scope = scope == null ? new LinkedHashSet<String>() : new LinkedHashSet<String>(scope);
        authorizationParameters.put(SCOPE, OAuth2Utils.formatParameterList(scope));
    }

    public void setResourceIds(Set<String> resourceIds) {
        this.resourceIds = resourceIds == null ? new HashSet<String>() : new HashSet<String>(resourceIds);
    }

    public void setApproved(boolean approved) {
        this.approved = approved;
    }

    public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
        this.authorities = authorities == null ? new HashSet<GrantedAuthority>() : new HashSet<GrantedAuthority>(
                authorities);
    }

    public void setAuthorizationParameters(Map<String, String> authorizationParameters) {
        String clientId = getClientId();
        Set<String> scope = getScope();
        this.authorizationParameters = authorizationParameters == null ? new HashMap<String, String>()
                : new HashMap<String, String>(authorizationParameters);
    }

    public void setApprovalParameters(Map<String, String> approvalParameters) {
        this.approvalParameters = approvalParameters == null ? new HashMap<String, String>()
                : new HashMap<String, String>(approvalParameters);
    }
    ....
}

On calling read on the above JSON string I get an exception

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "scope" (class de.mvbonline.vlx.auth.oauth2.DeserializedOAuth2Authentication), not marked as ignorable (3 known properties: "name", "authorizationRequest", "clientOnly"])
 at [Source: (String)"{        "credentials":"",        "clientOnly":false,        "authorizationRequest":{                "scope":["write","read"],                "resourceIds":["metadata"],                "approved":true,                "authorities":[],                "authorizationParameters":{                        "scope":"write read",                        "response_type":"token",                        "redirect_uri":"",                        "state":"",                        "stateful":"false",          "[truncated 316 chars]; line: 1, column: 111] (through reference chain: de.mvbonline.vlx.auth.oauth2.DeserializedOAuth2Authentication["scope"])

Of course the field "scope" is not in the context of DeserializedOAuth2Authentication, but in the context of DefaultAuthorizationRequest. Why is Jackson searching in the wrong class for it? I am unsing Jackson version 2.12.4

CodePudding user response:

Make sure that DefaultAuthorizationRequest can be serialized and deserialized by Jackson. I guess that they are not for several reasons. Two that I can think of:

Also, you can take a look at Map Serialization and Deserialization with Jackson

CodePudding user response:

I found my problem. I formerly mapped my concrete implementation of the interface AuthorizationRequest via a handler:

        mapper.addHandler(new DeserializationProblemHandler() {
            @Override
            public Object handleMissingInstantiator(DeserializationContext ctxt, Class<?> instClass, ValueInstantiator valueInsta, JsonParser p, String msg) throws IOException {
                if(instClass.isAssignableFrom(AuthorizationRequest.class)) {
                    return new DeserializedAuthorizationRequest();
                }
                return super.handleMissingInstantiator(ctxt, instClass, valueInsta, p, msg);
            }
        });

This seems to be definitely not the same as annotating the field with the concrete class. This now works without problems:

public class DeserializedOAuth2Authentication extends OAuth2Authentication{

    ...

    @Override
    @JsonProperty("authorizationRequest")
    @JsonDeserialize(as = DeserializedAuthorizationRequest.class)
    public AuthorizationRequest getAuthorizationRequest() {
        return authorizationRequest;
    }

    public void setAuthorizationRequest(AuthorizationRequest authorizationRequest) {
        this.authorizationRequest = authorizationRequest;
    }

}

  • Related