杰克逊 - 使用动态密钥对json进行序列化

时间:2016-02-17 18:54:44

标签: java json jackson

我有以下JSON:

{
  "2016-01-23": {
    "downloads": 4,
    "re_downloads": 1,
    "updates": 0,
    "returns": 0,
    "net_downloads": 4,
    "promos": 0,
    "revenue": "0.00",
    "returns_amount": "0.00",
    "edu_downloads": 0,
    "gifts": 0,
    "gift_redemptions": 0,
    "date": "2016-01-23"
  },
  "2016-01-24": {
    "downloads": 1,
    "re_downloads": 1,
    "updates": 0,
    "returns": 0,
    "net_downloads": 1,
    "promos": 0,
    "revenue": "0.00",
    "returns_amount": "0.00",
    "edu_downloads": 0,
    "gifts": 0,
    "gift_redemptions": 0,
    "date": "2016-01-24"
  }
}

如果每次更改日期,我该如何解析?我必须使用杰克逊进行解析。

1 个答案:

答案 0 :(得分:12)

如果您有动态密钥,则可以使用Map<K, V>。键的类型和值取决于您的需求。

最简单的方法是Map<String, Object>。你需要TypeReference<T>

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

假设您的密钥是有效日期,您可以使用Map<LocalDate, Object>

需要以下依赖项:

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

然后你可以:

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

最后,您可以将动态键的值映射到Java类。我们称之为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
}

然后你可以拥有Map<LocalDate, Foo>

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