1

I am working with jackson-core-2.8.3 and I have a json which has element provided in multiple cases. I want to map it to my class but I am not able to do so because I can have only one type of PropertyNamingStratergy in my class.

Example Json:-

{"tableKey": "1","not_allowed_pwd": 10}

There can be another json like

{"tableKey": "1","notAllowedPwd": 10}

ClassToMap :-

class MyClass {
public String tableKey;
public Integer notAllowedPwd;
}

ObjectMapper code :-

ObjectMapperobjectMapper=new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES,true);
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.setVisibility(PropertyAccessor.ALL,Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD,Visibility.ANY);
MyClass obj = objectMapper.readValue(s, MyClass.class);

I am not finding any solution anywhere. It will be good if anyone can help how to proceed.

Swaraj
  • 589
  • 4
  • 15

3 Answers3

0

Use jackson-annotations library and add @JsonProperty as below.

class MyClass {
  public String tableKey;
  @JsonProperty("not_allowed_pwd")
  public Integer notAllowedPwd;
}
kjsebastian
  • 1,259
  • 10
  • 16
  • Thanks, but i have different requirement, I have edited the question. – Swaraj Oct 25 '16 at 07:20
  • In that case, you would either have to 1) map to two different classes and combine manually, or 2) fix the schema of your json. I don't think changing/inconsistent property names could be mapped effortlessly – kjsebastian Oct 25 '16 at 07:24
  • Is there any class which is used during readValue method where I can modify property name to camelcase usinng my class – Swaraj Oct 25 '16 at 07:26
0

You can have a second setter with a @JsonProperty annotation for the second field name:

class MyClass {
    private String tableKey;
    private Integer notAllowedPwd;

    public String getTableKey() {
        return tableKey;
    }

    public void setTableKey(String tableKey) {
        this.tableKey = tableKey;
    }

    public Integer getNotAllowedPwd() {
        return notAllowedPwd;
    }

    public void setNotAllowedPwd(Integer notAllowedPwd) {
        this.notAllowedPwd = notAllowedPwd;
    }

    @JsonProperty("not_allowed_pwd")
    public void setNotAllowedPwd2(Integer notAllowedPwd) {
        this.notAllowedPwd = notAllowedPwd;
    }
}

Take into consideration that if the two properties are present in the json, they will be overwritten.

Franjavi
  • 647
  • 4
  • 14
0

Use these annotations on field:

@JsonProperty("not_allowed_pwd")
@JsonAlias("notAllowedPwd")
public Integer notAllowedPwd;