簡體   English   中英

Jackson用泛型反序列化JSON

[英]Jackson to deserialize JSON with generics

我對Jackson的多態性(是多態性)反序列化有一些問題。

假設我具有以下JSON結構

{
  "list": [
    "02/01/2018",
    "03/01/2018",
    "04/01/2018",
    "05/01/2018",
    "08/01/2018",
    "05/02/2018"
  ]
}

其中list可能包含不同類型的數據。 我已使用泛型使用以下POJO對數據結構進行了建模。

public class GeneralResponseList<T> extends BaseResponse {

    @JsonProperty("list")
    private List<T> list;

    @JsonProperty("paging")
    private Paging paging;

    @JsonProperty("sorting")
    private List<Sorting> sorting;

    // [CUT]
}

如何為T類型指定反序列化器? 我看過多態反序列化,但是我認為這不能解決我的問題。

我還可以創建擴展GeneralResponseList<LocalDate>的特定LocalDateResponseList 如何為特定響應指定反序列化器?

您能給我建議解決方案還是提示解決此問題。

假設您有一個類似的課程:

public class GeneralResponseList<T> {

    @JsonProperty("list")
    private List<T> list;

    // Getters and setters
}

您可以使用TypeReference<T>

GeneralResponseList<LocalDate> response = 
    mapper.readValue(json, new TypeReference<GeneralResponseList<LocalDate>>() {});

如注釋中所述,如果您有多種日期格式,則可以編寫一個自定義反序列化器來處理:

public class LocalDateDeserializer extends StdDeserializer<LocalDate> {

    private List<DateTimeFormatter> availableFormatters = new ArrayList<>();

    protected LocalDateDeserializer() {
        super(LocalDate.class);
        availableFormatters.add(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
        availableFormatters.add(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    @Override
    public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) 
            throws IOException {

        String value = p.getText();

        if (value == null) {
            return null;
        }

        for (DateTimeFormatter formatter : availableFormatters) {
            try {
                return LocalDate.parse(value, formatter);
            } catch (DateTimeParseException e) {
                // Safe to ignore
            }
        }

        throw ctxt.weirdStringException(value, LocalDate.class, "Unknown date format");
    }
}

然后將反序列化器添加到模塊中,然后在ObjectMapper實例中注冊該Module

ObjectMapper mapper = new ObjectMapper();

SimpleModule module = new SimpleModule();
module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
mapper.registerModule(module);

暫無
暫無

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

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