I'm working on a Spring MVC project and I'm trying to implement an anonymous chat. In one of the classes, named Conversation, I have several fields such as id, startDate, and preserved and some others. I want Jackson to ignore these other fields using the @JsonIgnoreProperties
annotation, and I also want them to not be persisted in the database by using the @Transient
annotation. I've generated the getters and setters using Lombok.
Initially, I had a code snippet that worked well. It was responsible for displaying a user's persisted conversations on the /conversations page. Here's the code snippet I was using:
model.addAttribute("conversations",
objectMapper.writeValueAsString(userConversations));
This code has working fine until I've added field randomTopics
and method getRandomTopic()
to my Conversation class. The method is designed to get random topic if one of the users in conversation has requested it.
@Transient
private List<String> randomTopics;
//...
public String getRandomTopic() {
return randomTopics.get(new Random().nextInt(randomTopics.size()));
}
The randomTopics
list is initialized from a txt file and isn't stored in the database. The problem arises when a user wants to view their previous conversations. The application retrieves the conversations from the database, but the randomTopics
field remains null. Strangely, Jackson seems to be calling the getRandomTopic()
method during the mapping process, which causes a JsonMappingException and a NullPointerException in the getRandomTopic()
method.
Interestingly, I noticed that if I remove the 'get' prefix from the method name (getRandomTopic()
becomes randomTopic()
), the issue disappears. However, the problem resurfaces if the method name starts with 'get'. Why does this happen?
There's another curious aspect: I also have a Map field in the same class, similar to the randomTopics
list. This field is also ignored by Jackson, and it has a method that starts with "get" to retrieve some topic from Map. The difference lies in the return type of this method; it returns a custom class instead of a String. In this case, Jackson never calls the method (I verified this with a debugger).
Any insights into why this is happening would be greatly appreciated. Thank you for your time!