How to specify jackson to only use fields - preferably globally

前端 未结 8 677
旧巷少年郎
旧巷少年郎 2020-11-22 17:03

Default jackon behaviour seems to use both properties (getters and setters) and fields to serialize and deserialize to json.

I would like to use the fields as the ca

8条回答
  •  遥遥无期
    2020-11-22 17:48

    How about this: I used it with a mixin

    non-compliant object

    @Entity
    @Getter
    @NoArgsConstructor
    public class Telemetry {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long pk;
        private String id;
        private String organizationId;
        private String baseType;
        private String name;
        private Double lat;
        private Double lon;
        private Instant updateTimestamp;
    }
    

    Mixin:

    @JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE, setterVisibility = NONE)
    public static class TelemetryMixin {}
    

    Usage:

        ObjectMapper om = objectMapper.addMixIn(Telemetry.class, TelemetryMixin.class);
        Telemetry[] telemetries = om.readValue(someJson, Telemetry[].class);
    

    There is nothing that says you couldn't foreach any number of classes and apply the same mixin.

    If you're not familiar with mixins, they are conceptually simply: The structure of the mixin is super imposed on the target class (according to jackson, not as far as the JVM is concerned).

提交回复
热议问题