Spring-Data-REST: HAL 中@Embeddable 的自定义序列化

Spring-Data-REST: Custom serialization of @Embeddable in HAL

我有一个看起来像这样的实体(为了简洁起见,我将省略 getter、setter 和构造函数):

@Entity
public class System {
    @NotNull
    @Column(name = "SYSTEMID", nullable = false)
    @Embedded
    private SystemId systemId;
}

SystemId 如下所示:

@Embeddable
@JsonSerialize(using = SystemIdSerializer.class)
@JsonDeserialize(using = SystemIdDeserializer.class)
public class SystemId {
    @Column(name = "SYSTEMID", nullable = false)
    private String value;
}

我的自定义序列化程序只写出值,它适用于 'normal' JSON,只是不适用于如下所示的 HAL 表示:

{
    "systemId": {
        "content": "1"
    }
}

我想要这样

{
    "systemId": "1"
}

还有。 有什么办法吗?我花了一些时间谷歌搜索但没有成功。 谢谢。

也许 projection 可以帮助你...

@Projection(name="withSystemId", types = System.class)
public interface WithSystemId {

    @JsonProperty("systemId")
    @Value("#{target.systemId.value}")
    String getSysId();

    // Other getters of System properties...
}

然后尝试获取您的 System

http://localhost:8080/api/systems?projection=withSystemId

已更新

关于自定义序列化程序 - 只需将 @JsonUnwrapped 注释添加到 systemId:

@Entity
public class System {

    @Embedded
    @JsonUnwrapped
    private SystemId systemId;
} 

那么你一定会如愿以偿

{
    "systemId": "1"
} 

而且我假设您的序列化程序如下所示:

public class SystemIdSerializer extends StdSerializer<SystemId> {

    public SystemIdSerializer() {
        this(null);
    }

    protected SystemIdSerializer(Class<SystemId> t) {
        super(t);
    }

    @Override
    public void serialize(SystemId id, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        gen.writeNumberField("systemId", id.value());
        gen.writeEndObject();
    }
}

工作示例是 here. See Member and nested MemberSkill classes. Then try to launch the app and GET http://localhost:8080/api/members