如何仅序列化杰克逊的孩子的 ID [英] How to serialize only the ID of a child with Jackson

查看:9
本文介绍了如何仅序列化杰克逊的孩子的 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a built-in way to only serialize the id of a child when using Jackson (fasterxml.jackson 2.1.1)? We want to send an Order via REST which has a Person reference. The person object however is quite complex and we could refresh it on the server side, so all we need is the primary key.

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

Or do I need a custom serializer for this? Or do I need to @JsonIgnore all other properties? Would that prevent the Person data from being sent back when requesting an Order object? I'm not sure yet if I'll need that but I'd like to have control over it if possible...

推荐答案

有几种方法.第一个是使用 @JsonIgnoreProperties 从子节点中删除属性,如下所示:

There are couple of ways. First one is to use @JsonIgnoreProperties to remove properties from a child, like so:

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

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

another possibility, if Child object is always serialized as id:

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

还有一种方法是使用 @JsonIdentityInfo

and one more approach is to use @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 以外的属性.然而,结果不会被包装为对象.

which would also work for serialization, and ignore properties other than id. Result would not be wrapped as Object however.

这篇关于如何仅序列化杰克逊的孩子的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆