且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Jackson - 使用动态密钥对 json 进行反序列化

更新时间:2022-10-14 20:59:43

When you have dynamic keys, you can use a Map<K, V>. The type of the keys and the values depend on your needs.


The simplest approach is Map<String, Object>. You'll need a TypeReference<T> for that:

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = 
    mapper.readValue(json, new TypeReference<Map<String, Object>>() {});


Assuming that your keys are valid dates, you could use a Map<LocalDate, Object>.

The following dependency is required:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>${jackson.version}</version>
</dependency>

Then you can have:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
Map<LocalDate, Object> map =
    mapper.readValue(json, new TypeReference<Map<LocalDate, Object>>() {});


Finally, you could map the values of the dynamic keys to a Java class. Let's call it Foo:

public class Foo {

    private Integer downloads;

    @JsonProperty("re_downloads")
    private Integer reDownloads;

    private Integer updates;

    private Integer returns;

    @JsonProperty("net_downloads")
    private Integer netDownloads;

    private Integer promos;

    private String revenue;

    @JsonProperty("returns_amount")
    private String returnsAmount;

    @JsonProperty("edu_downloads")
    private Integer eduDownloads;

    private Integer gifts;

    @JsonProperty("gift_redemptions")
    private Integer giftRedemptions;

    // Default constructor, getters and setters omitted
}

And then you can have a Map<LocalDate, Foo>:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
Map<LocalDate, Foo> map =
        mapper.readValue(json, new TypeReference<Map<LocalDate, Foo>>() {});