How to ignore @JsonProperty while converting object to map by Jackson

LHCHIN :

For example, I have a class User which has only 2 fields - name and identification which annotated by @JsonProperty respectively. And I use Jackson to convert this object to a Map, but the result is not what I expected. I want to the all the keys in the result map to be what I declared in User, not the value in @JsonProperty.

Class User

class User {
    @JsonProperty("username")
    private String name;

    @JsonProperty("id")
    private int identification;

    //constructor, getters, setters and toString
}

Code snippet

ObjectMapper mapper = new ObjectMapper();
User user = new User("Bob", 123);
System.out.println(user.toString());

Map<String, Object> result = mapper.convertValue(user, Map.class);
System.out.println(result.toString());

Console output

User [name=Bob, identification=123]
{username=Bob, id=123}

But what I expected output for map is as follows. The field name should be the same defined in class User, not the value specified in @JsonProperty. BTW, I cannot remove the @JsonProperty because they are used for serialization/deserialization somewhere.

{name=Bob, identification=123}

Any advice and suggestions will be greatly appreciated. Thanks!

Maxim Popov :

You have to configure your object mapper like this (but it will ignore all annotation)

ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.USE_ANNOTATIONS);

I have found another way that turns off only name setting from @JsonProperty and leave another property from @JsonProperty and another Jackson annotations. If you want to turn off some extra annotations(or part of annotation) - override method which implements it

mapper.setAnnotationIntrospector( new JacksonAnnotationIntrospector() {
            @Override
            public PropertyName findNameForSerialization(Annotated a) {
                return null;
            }
        });

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=421214&siteId=1