Jackson - 使用动态键反序列化 json

2022-09-03 02:01:38

我有以下 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

当您具有动态键时,可以使用 Map<K、V>。键的类型和值取决于您的需要。


最简单的方法是 。为此,您需要一个 TypeReference<T>Map<String, Object>

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>>() {});

答案 2