当您具有动态键时,可以使用 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>>() {});