Title: ObjectMapper not considering annotations
Tags: java;json;rest;jackson
Question: I have the below piece of code which would convert an annotated Java object into Json String.
try {
String jsonString = mapper.writeValueAsString(obj);
LOGGER.debug("logAsJson", jsonString);
} catch (Exception e) {
LOGGER.warn("logAsJson", "Exception in logging only. Nothing critical! ", e);
}
And my class would look something like this
public class Car {
@JsonProperty("capabilities")
private List<Capability&gt; capability = new ArrayList<Capability&gt;();
@JsonProperty("periodicity")
@NotNull
private Periodicity periodicity;
@JsonProperty("car_driver")
private List<carDriver&gt; carDriver = new ArrayList<carDriver&gt;();
Problem is that while creating the json string from the object, object mapper is not considering the annotations for field names.
Thanks in advance.
Comment: Check if you have jackson 1 and jackson 2 in your classpath, and if you're using mapper from one version and annotations from the other one.

Comment: That was my thought also, check the annotation you are using matches the library you are using.

Comment: That worked Guys, Thanks a lot :)

Comment: @Ajay How did you fixed this issue ?. I am also facing the same prob


Here is another answer: You might have imported the json annotation and the object mapper from different library versions. Make sure they are from the same library.
Example,
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:09/18/15', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java><json><rest><jackson>', 'Title': 'ObjectMapper not considering annotations', 'ViewCount': 2357, 'id': 32659915, 'user_AboutMe': '<p>Very much enthusiastic about java and related technologies</p>\n\n<h1>SOreadytohelp</h1>\n', 'user_AccountId': 220904.0, 'user_DisplayName': 'Ajay', 'user_Reputation': 2776.0, 'user_Views': 183.0, 'user_id': 478587.0}}