【问题标题】:Quarkus REST client avoid JSON serialization of Null FieldsQuarkus REST 客户端避免空字段的 JSON 序列化
【发布时间】:2020-07-13 17:26:29
【问题描述】:

我需要在远程服务上发送更新请求以更新某些字段。远程服务使用application/json 内容类型,所以我实现了我的休息客户端:

@RegisterRestClient
@Path("/api/v1")
@Produces("application/json")
@Consumes("application/json")
@ApplicationScoped
public interface ServiceClient {
    @POST
    @Path("/path_to_update/{uuid}")
    Response updateAttributes(
        @PathParam("uuid") String uuid,
        Attributes attributes
    );
}


@NoArgsConstructor
@Data
@AllArgsConstructor
@Builder
public class Attributes {
    private AttributesA a;
    private AttributesB b;
}

@NoArgsConstructor
@Data
@AllArgsConstructor
@Builder
public class AttributesA {
    private String field1;
}

@NoArgsConstructor
@Data
@AllArgsConstructor
@Builder
public class AttributesB {
    private String field2;
    private String field3;
}

我只需要更新部分字段。也许field1field3。所以在这种情况下,field2 将被设置为null

远程服务不接受null 作为参数值,因此我需要避免序列化所有具有null 值的字段。

我的项目使用jsonb,我已经尝试用JsonbNillable注释模型类,但没有任何成功。

有没有办法配置rest客户端来避免空字段的序列化?

【问题讨论】:

    标签: java json serialization quarkus jsonb-api


    【解决方案1】:

    我建议将 Lombok 删除为您的数据类,以便在事情没有按预期工作时更加清晰。在这种情况下,您实际上可以使用 JSON-B 的默认可见性策略在没有 lombok 的情况下更简洁地编写代码,这意味着公共字段会自动 [de]serailized 并且不需要具有 getter/setter。

    所以你的数据类可能是:

    public class Attributes {
        public AttributesA a;
        public AttributesB b;
    }
    
    public class AttributesA {
        public String field1;
    }
    
    public class AttributesB {
        public String field2;
        public String field3;
    }
    

    有没有办法配置rest客户端以避免空字段的序列化?

    默认情况下 JSON-B 不会序列化空值。所以如果我们这样做了:

    Attributes empty = new Attributes();
    String json = jsonb.toJson(empty);
    System.out.println(json); // "{}"
    

    我们只会得到一个空的 JSON 对象 {}。如果您确实想将空值序列化为null@JsonbNillable 注释很有用。

    【讨论】:

    • 我终于找到了真正的问题。当所有类的字段都是null 时,序列化程序会创建一个没有字段的 Json 对象(这是正确的),但是我尝试调用的远程服务不是这样的。
    猜你喜欢
    • 2022-11-09
    • 2020-02-15
    • 2022-01-08
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2022-07-14
    • 2013-11-02
    • 2017-04-26
    相关资源
    最近更新 更多