Jackson Java to JSON object mapper changes field name

Using Jackson to convert a Java object to JSON

ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); jsonMessage = mapper.writeValueAsString(object); 

the result is that the participants field (which is part of the object instance)

 participants Arrays$ArrayList<E> 

renamed to "membersList"

 participantsList":[{"userId":"c1f9c"}] 

i.e. A list is added to the field name. I looked through Jackson's documentation, but found no way to prevent this. Is it possible? Testing the above code in a separate project does not lead to the same result (i.e. renaming does not occur). Why is Jackson acting like this? Unfortunately, the object is a third party, and I cannot change it.

Using Jackson's 2.3.3 version (the same behavior is confirmed since 2.9.0).

+8
java json jackson objectmapper
source share
2 answers

Alexander's comment pointed in the right direction. Actually there is getParticipantsList (), which Jackson apparently takes into account when determining the JSON field name. However, as I wrote earlier, I cannot make any changes there, given that this is a third-party object.

But, with a better understanding of what causes the problem, I was able to come up with a solution:

 mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY).withGetterVisibility(Visibility.NONE).withIsGetterVisibility(Visibility.NONE)); 

or

 mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE); mapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE); 
+4
source share

Perhaps you can use USE_ANNOTATIONS to skip annotations as follows:

  ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(MapperFeature.USE_ANNOTATIONS, false); String jsonMessage = mapper.writeValueAsString(object); 
-one
source share

All Articles