java - 如何仅序列化 Jackson 的 child 的 ID

标签 java json serialization jackson

在使用 Jackson (fasterxml.jackson 2.1.1) 时,是否有一种仅序列化 child id 的内置方法?我们想通过具有 Person 引用的 REST 发送一个 Order。但是 person 对象非常复杂,我们可以在服务器端刷新它,所以我们只需要主键。

或者我需要一个自定义序列化器吗?还是我需要 @JsonIgnore 所有其他属性?在请求 Order 对象时,这会阻止 Person 数据被发回吗?我还不确定我是否需要它,但如果可能的话,我想控制它......

最佳答案

有几种方法。第一个是使用 @JsonIgnoreProperties 来移除子元素的属性,如下所示:

public class Parent {
   @JsonIgnoreProperties({"name", "description" }) // leave "id" and whatever child has
   public Child child; // or use for getter or setter
}

另一种可能性,如果子对象总是序列化为 id:

public class Child {
    // use value of this property _instead_ of object
    @JsonValue
    public int id;
}

另外一种方法是使用 @JsonIdentityInfo

public class Parent {
   @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
   @JsonIdentityReference(alwaysAsId=true) // otherwise first ref as POJO, others as id
   public Child child; // or use for getter or setter

   // if using 'PropertyGenerator', need to have id as property -- not the only choice
   public int id;
}

这也适用于序列化,并忽略 id 以外的属性。但是,结果不会被包装为 Object。

关于java - 如何仅序列化 Jackson 的 child 的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17542240/

相关文章:

javascript - 从嵌套 JSON 检索数据到 Morris.js xkey

java - 尝试读取 json 文件时出现 JsonParserException

javascript - PHP 序列化失败并以半序列化格式存储

java - 有什么方法可以知道 Android 上的 Parcel 中的对象是什么类型?

即使为表单元素定义了 name 属性,JQuery form.serialize() 也会返回空字符串

java - 调色板的连续颜色

java - Oracle 数据库元数据的 NUMBER 数据类型的默认值有什么意义吗?

java - 仅在级别为调试时打印堆栈跟踪

javascript - 嵌套 JSON 查找项

java - 为什么此代码不起作用?-通过扫描仪和 PrintWriter 归档