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!
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;
}
});
You just simply remove the JsonProperty. Then it will automatically map to the property name.
JsonProperty
annotation just help you specify the field name which is different to your property name.
从字段中删除@JsonProperty
I know several ways to achieve it:
Is to use @JsonSetter & @JsonGetter to manipulate serialization/deserialization names. An example:
@JsonGetter("name") public String getName() { return name; } //# Used during deserialization @JsonSetter("username") public void setName(String name) { this.name = name; }
To use @JsonAlias to provide an alias for desirialization
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.