Search code examples
javaandroidjsonjacksonfasterxml

Make JsonGetter case insensitive


I'm using JacksonAnnotation along with Spring Framework to parse a JSON that I get from a web service for my app.

I have the same data structure coming from two distinct methods but there is a field in one of them that comes capitalized. I don't want to create two data structures just because of that.

Is there any way that I make JsonGetter case insensitive or at least make it accept two version of a string?

Currently I have to use this for method A

@JsonGetter("CEP")
public String getCEP() {
    return this.cep;
}

and this for method B

@JsonGetter("Cep")
public String getCEP() {
    return this.cep;
}

Thanks


Solution

  • You can create new setter method for each possibility of property name:

    import com.fasterxml.jackson.annotation.JsonSetter;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class JacksonProgram {
    
        public static void main(String[] args) throws Exception {
            ObjectMapper mapper = new ObjectMapper();
            System.out.println(mapper.readValue("{\"Cep\":\"value\"}", Entity.class));
            System.out.println(mapper.readValue("{\"CEP\":\"value\"}", Entity.class));
        }
    }
    
    class Entity {
    
        private String cep;
    
        public String getCep() {
            return cep;
        }
    
        @JsonSetter("Cep")
        public void setCep(String cep) {
            this.cep = cep;
        }
    
        @JsonSetter("CEP")
        public void setCepCapitalized(String cep) {
            this.cep = cep;
        }
    
        @Override
        public String toString() {
            return "Entity [cep=" + cep + "]";
        }
    }