【问题标题】:Spring-Data-REST: Custom serialization of @Embeddable in HALSpring-Data-REST:HAL 中 @Embeddable 的自定义序列化
【发布时间】:2017-11-26 19:26:07
【问题描述】:

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

@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;
}

我的自定义序列化程序只写出值,它适用于“普通”JSON,而不是看起来像这样的 HAL 表示:

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

我想要这样的

{
    "systemId": "1"
}

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

【问题讨论】:

    标签: json spring-data-rest hateoas hal


    【解决方案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。请参阅 Member 和嵌套的 MemberSkill 类。然后尝试启动应用程序并获取http://localhost:8080/api/members

    【讨论】:

    • 谢谢,我会试试的,但是不应该没有投影就可以吗?当我使用自定义序列化程序发布内容时,Spring 能够反序列化它。我只是不明白为什么它不使用自定义序列化程序。
    • @N4zroth 也许有必要明确注册自定义序列化程序。我已经更新了我的答案。
    • @N4zroth 无需注册自定义序列化程序,只需使用 @JsonUnwrapped.. 我已经更新了答案
    • 太棒了,谢谢,@JsonUnwrapped 正在做我想做的事。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 2017-11-17
    • 2022-07-21
    • 2018-02-19
    • 2014-05-02
    • 1970-01-01
    相关资源
    最近更新 更多