我正在寻找一种通过 jackson 将部分对象(不是它的所有属性)转换为 json 的方法。目前我正在使用这个解决方案:
User userServed = User.find.byId(id);
ObjectMapper mapper = new ObjectMapper();
JsonNode node = null;
node = mapper.convertValue(userServed, JsonNode.class);
到目前为止,一切正常。
我的问题是,我不想将对象中的很多属性暴露给列表等 json 节点。有没有办法只选择所需的属性?
最佳答案
您可以使用 JsonIgnore
注释该字段吗?
来自http://wiki.fasterxml.com/JacksonAnnotations
@JsonIgnore (method/field): annotation used to completely disregard annotated method, regardless of auto-detection or other annotations
编辑:或者使用注释JsonIgnoreProperty
。
(Jackson 1.4+) @JsonIgnoreProperties (class) can be used to indicate that certain properties are to be ignored for serialization and/or deserialization (handling differs a bit depending on which operation is affected):
◦String[] value() defines logical property names to ignore (names derived from getter/setter names, or by explicit annotations)
◦boolean ignoreUnknown() defines whether "unknown" JSON properties can be silently ignored during deserialization or not; does not affect serialization.
关于java - 如何使用 Jackson 对象映射器将 Java 对象中的并非所有属性转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35848506/