This is roughly my code.
I am trying to have Jackson ignore a field when it takes my POJO and creates JSON out of it:
import com.fasterxml.jackson.annotation.JsonIgnore;
public class MyPOJO {
@JsonIgnore
private String socialSecurityNumber = "111-11-1111";
// ...
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
// ...
}
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class FormatAlerts {
List<Message> alerts = new ArrayList<>();
public FormatAlerts(List<Message>alerts) {
this.alerts = alerts;
}
public List<String> formatAlerts() {
List<String> formattedAlerts = new ArrayList<>();
ObjectMapper om = new ObjectMapper();
try {
for(Message m : alerts) {
String alert = om.defaultPrettyPrintingWriter()
.writeValueAsString(m);
formattedAlerts.add(alert);
}
} catch(Exception e) {
e.printStackTrace();
}
return formattedAlerts;
}
}
The JSON is ouputted fine, but the class members that have @JsonIgnore are NOT ignored.
I have these dependencies in my Maven pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-xc</artifactId>
<version>1.9.12</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.14.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.14.2</version>
</dependency>
</dependencies>
Those are my only Jackson and Json entries in my pom.xml
Do I need a different combination of versions?
2
Answers
Please add the jackson dependencies as follows. Remove the others.
Long story short, you are mixing two incompatible libraries.
Jackson project was originally started under Codehaus project, but at least 10 years ago it was moved.
The
jackson-xc
released in 2013 underorg.codehaus
namespace.You are using an ObjectMapper in
FormatAlerts
That kind of ObjectMapper using own
@JsonIgnore
annotation which placed underorg.codehaus.jackson.annotate.JsonIgnore
.In fact, the ObjectMapper from
org.codehaus
project doesn’t recognize the@JsonIgnore
annotaion fromcom.fasterxml
namespace.You should consolidate those project. I strongly recommend use
com.fasterxml
becauseorg.codehaus
is no longer maintained.Step 1.
was moved to
Step 2.
Now, the right dependency included, but it has some changes.
Import
ObjectMapper
from the right packageDon’t worry it also have pretty print feature, but the method name changed.