Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - De-Serialize json with dynamic key

Tags:

java

json

jackson

I have the following 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"
  }
}

How can I parse this, when the date will change everytime? I must use Jackson to do the parsing.

like image 682
Jim's Code Corner Avatar asked Feb 17 '16 18:02

Jim's Code Corner


1 Answers

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>>() {});
like image 57
cassiomolin Avatar answered Oct 20 '22 22:10

cassiomolin