Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Java to JSON object mapper modifies field's 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 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).

like image 910
heeboir Avatar asked Aug 04 '17 12:08

heeboir


People also ask

How do you change a field name in Java?

In order to change the field name, we use the @JsonProperty annotation. In the annotation constructor, we pass the name of the property. Let's take an example to understand how we can use @JsonProperty annotation to change the name of the field for serialization.

How does Jackson ObjectMapper work?

The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON. The Jackson ObjectMapper can also create JSON from Java objects.

How does Jackson deserialize dates from JSON?

In order to correct deserialize a Date field, you need to do two things: 1) Create a custom deserializer by extending StdDeserializer<T> class and override its deserialize(JsonParser jsonparser, DeserializationContext context) method. This method should return a Date if we are using this to parse a date field in JSON.


1 Answers

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);
like image 98
heeboir Avatar answered Oct 11 '22 21:10

heeboir