簡體   English   中英

帶有@JsonProperty 的自定義序列化器和反序列化器 - Java

[英]Custom serialiser and deserialiser with @JsonProperty - Java

我的 class 看起來像這樣,

@Getter
@ToString
@EqualsAndHashCode
public class Clazz {

    private String a;
    private long b;
    private CustomObject c;
    private List<String> d;

    @Builder
    @JsonCreator
    public Clazz(@JsonProperty(“a”) String a,
                     @JsonProperty(“b”) long b,
                     @JsonProperty(“c”) CustomObject c,
                     @JsonProperty(“d”) List<String> d) {

        this.a = a; 
        this.b = b; 
        this.c = c; 
        this.d = d; 
    }
}

我在反序列化CustomObject時遇到問題。 如何僅為 CustomObject 編寫自定義序列化器和反序列化器?

我用於反序列化和序列化的 ObjectMapper,

        objectMapper = spy(JsonMapper.builder()
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .addModule(new GuavaModule())
                .addModule(new ParameterNamesModule())
                .serializationInclusion(JsonInclude.Include.NON_NULL)
                .activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS)
                .build());

我無法更改 CustomObject class,因此只需要在此 class 中處理序列化/反序列化。

先感謝您。

您可以在Clazz中的CustomObject字段頂部使用以下注釋

@JsonSerialize(using = CustomObjectSerializer.class)
private CustomObject c;
public class CustomObjectSerializer extends StdSerializer<CustomObject> {
 public CustomObjectSerializer() {
        this(null);
    }
  
    public CustomObjectSerializer(Class<CustomObject> t) {
        super(t);
    }

    @Override
    public void serialize(
      Item value, JsonGenerator jgen, SerializerProvider provider) 
      throws IOException, JsonProcessingException {
 
        jgen.writeStartObject();
        jgen.writeNumberField("id", value.id);
        jgen.writeStringField("name", value.name);
        jgen.writeEndObject();
    }
}

並按如下方式注冊該序列化程序

SimpleModule module = new SimpleModule();
module.addSerializer(CustomObject.class, new CustomObjectSerializer());
objectMapper.registerModule(module);

檢查以下資源:

  1. https://www.baeldung.com/jackson-custom-serialization
  2. https://stackoverflow.com/a/20530302/2534090
  3. https://stackoverflow.com/a/10835504/2534090

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM