java - 如何使用 Jackson 对象映射器将 Java 对象中的并非所有属性转换为 json

标签 java json jackson

我正在寻找一种通过 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/

相关文章:

javascript json - 从 php 解码 ajax json 数组时出现问题

php - 如何修复 JSON_ERROR_UTF8

java - Jackson XML Bind Element 基于属性值

java - 在自定义反序列化器中调用默认反序列化器不会影响实例

java - 字符串标记化以删除一些数据

java方法防止并发访问

Java、Spring 将主题属性文件 Hook 到 css 文件

java - 我在缩放使用 View 的基于H2的Java应用程序时遇到问题

javascript - 多系列数据 Highcharts 线

java - com.fasterxml.jackson.core.JsonParseException : Unrecognized character escape 'U' (code 85)