首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jackson用泛型反序列化JSON

Jackson用泛型反序列化JSON
EN

Stack Overflow用户
提问于 2018-07-05 10:11:49
回答 1查看 1.1K关注 0票数 1

我对多态有一些问题(是多态的吗?)和杰克逊进行反序列化。

假设我有以下JSON结构

代码语言:javascript
复制
{
  "list": [
    "02/01/2018",
    "03/01/2018",
    "04/01/2018",
    "05/01/2018",
    "08/01/2018",
    "05/02/2018"
  ]
}

其中list可能包含不同类型的数据。我使用泛型用下面的POJO对数据结构进行建模。

代码语言:javascript
复制
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类型指定反序列化器?我看过多态反序列化,但我认为它不能解决我的问题。

我还可以创建一个特定的LocalDateResponseList,它扩展了GeneralResponseList<LocalDate>。如何为特定响应指定反序列化器?

你能给我一个解决这个问题的办法或提示吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-05 10:25:21

假设您有一个类,如:

代码语言:javascript
复制
public class GeneralResponseList<T> {

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

    // Getters and setters
}

您可以使用TypeReference

代码语言:javascript
复制
GeneralResponseList<LocalDate> response = 
    mapper.readValue(json, new TypeReference<GeneralResponseList<LocalDate>>() {});

如果您有多个日期格式(正如您在注释中提到的那样),您可以编写一个自定义反序列化器来处理这个问题:

代码语言:javascript
复制
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");
    }
}

然后将反序列化器添加到模块中,并在Module实例中注册ObjectMapper

代码语言:javascript
复制
ObjectMapper mapper = new ObjectMapper();

SimpleModule module = new SimpleModule();
module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
mapper.registerModule(module);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51188665

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档