JsonIgnore annotation doesn\'t seem to work for me. Any ideas why?
public class JsonTest implements Serializable {
@JsonIgnore
private static JsonTest i
Transient means that that field will not be serialized. You do not need to add @JsonIgnore annotation there because of that field will be excluded anyway.
You can locate @JsonIgnore annotation at least in org.codehaus.jackson:jackson-mapper-asl:1.9.13 and com.fasterxml.jackson.core:jackson-annotations:2.4.3 (this is what I used). Where ObjectMapper is in jackson-mapper-asl artifact. The interesting part here is that if I use @JsonIgnore from jackson-annotations (com.fasterxml.jackson.annotation.JsonIgnore) -- it doesn't work ('set' is in response) even if I configure ObjectMapper to use only properties. Probably it is a bug in fasterxml implementation but I didn't find it.
So, it is working fine if you will use codehaus rather then fasterxml (I added configuration to use only fields):
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
public class JsonTest implements Serializable {
@JsonIgnore
private static JsonTest instance = null;
private transient Set set = new CopyOnWriteArraySet();
private JsonTest() {}
@JsonIgnore
public static JsonTest getInstance() {
if (instance == null)
instance = new JsonTest();
return instance;
}
public void setSet(Set set) {
this.set = set;
}
@JsonIgnore
public Set getSet() {
return set;
}
public String toString() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
try {
return mapper.writeValueAsString(this);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
HashSet set = new HashSet();
set.add("test");
JsonTest.getInstance().setSet(set);
System.out.println(JsonTest.getInstance().toString());
}
}