简体   繁体   中英

Not able to convert json to pojo class, getting com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException exception

This is my JsonObject

JSONObject input = new JSONObject("{\n" + 
                "   \"ColumnNames\":[\"col1\", \"col2\", \"col3\", \"col4\", \"col5\"]\n" + 
                "}");

My POJO Class

public class RequestClass {
    private List<String> ColumnNames;

    public void setColumnNames(List<String> ColumnNames) {
        this.ColumnNames = ColumnNames;
    }

    public List<String> getColumnNames() {
        return this.ColumnNames;
    }
}

Trying to convert JsonObject to pojo class object with the help of ObjectMapper as shown below -

ObjectMapper mapper = new ObjectMapper();
//mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

RequestClass request = null;
try {
    request = mapper.readValue(input.toString(), RequestClass.class);
} catch (Exception e) {
    e.printStackTrace();
} 

Getting an exception in output

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "ColumnNames" (class RequestClass), not marked as ignorable (one known property: "columnNames"])
 at [Source: {"ColumnNames":["col1","col2","col3","col4","col5"]}; line: 1, column: 17] (through reference chain: RequestClass["ColumnNames"])

The name of the private property named ColumnNames is actually irrelevant. The property is found by introspection, looking at the getters and setters. And by convention, if you have methods named getColumnNames and setColumnNames , they define a property named columnNames (lowercase c ).

So you have two choices:

  • change the name of the property in the JSON to columnNames , or
  • use an annotation to override the default introspective behavior.

The latter is achieved by using the @JsonProperty on the getter and setter, as follows:

    @JsonProperty("ColumnNames")
    public List<String> getColumnNames() {
        return this.ColumnNames;
    }

Looking at the exception it looks like in the pojo , you have mentioned ColumnNames and in the json you have mentioned columnNames (a case mismatch) , although you have defined it correctly in the json example above. Please check whether there is a case mismatch in the field names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM