JsonIgnore注释似乎对我不起作用.有什么想法吗?
public class JsonTest implements Serializable {
@JsonIgnore
private static JsonTest instance = null;
@JsonIgnore
private transient Set<String> set = new CopyOnWriteArraySet<String>();
private JsonTest() {}
@JsonIgnore
public static JsonTest getInstance() {
if (instance == null)
instance = new JsonTest();
return instance;
}
public void setSet(Set<String> set) {
this.set = set;
}
@JsonIgnore
public Set<String> getSet() {
return set;
}
public String toString() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
try {
return mapper.writeValueAsString(this);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
set.add("test");
JsonTest.getInstance().setSet(set);
System.out.println(JsonTest.getInstance().toString());
}
}
输出:{“set”:[“test”]}
最佳答案 瞬态意味着该字段不会被序列化.您不需要在那里添加@JsonIgnore注释,因为无论如何都会排除该字段.
您至少可以在org.codehaus.jackson中找到@JsonIgnore注释:jackson-mapper-asl:1.9.13和com.fasterxml.jackson.core:jackson-annotations:2.4.3(这是我使用的). ObjectMapper位于jackson-mapper-asl工件中.这里有趣的部分是,如果我使用来自jackson-annotations的@JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) – 即使我将ObjectMapper配置为仅使用属性,它也不起作用(‘set’响应) .可能它是fastxml实现中的一个错误,但我没有找到它.
所以,如果你使用codehaus而不是fastxml(我添加配置只使用字段),它工作正常:
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<String> set = new CopyOnWriteArraySet<String>();
private JsonTest() {}
@JsonIgnore
public static JsonTest getInstance() {
if (instance == null)
instance = new JsonTest();
return instance;
}
public void setSet(Set<String> set) {
this.set = set;
}
@JsonIgnore
public Set<String> 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<String> set = new HashSet<String>();
set.add("test");
JsonTest.getInstance().setSet(set);
System.out.println(JsonTest.getInstance().toString());
}
}