Reputation: 739
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 field "participants" (which is part of the object instance)
participants Arrays$ArrayList<E>
gets renamed to "participantsList"
participantsList":[{"userId":"c1f9c"}]
i.e. "List" is appended to the field name. I went through the Jackson documentation but haven't found a way to prevent this from happening. Is this possible? Testing the above code in a standalone project does not cause the same result (i.e. no renaming takes place). Why is Jackson behaving like this? Unfortunately, the object is third party and I cannot change it.
Using Jackson version 2.3.3 (same behaviour verified with 2.9.0).
Upvotes: 8
Views: 2418
Reputation: 42
Maybe you can use USE_ANNOTATIONS to skip annotations like this:
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(MapperFeature.USE_ANNOTATIONS, false);
String jsonMessage = mapper.writeValueAsString(object);
Upvotes: -1
Reputation: 739
Oleksandr's comment pointed in the right direction. Indeed there is a getParticipantsList() that Jackson seems to take into account when determining the JSON field name. However, as I wrote before, I am not able to make any changes there, considering it 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);
Upvotes: 4