0

I have a JSON file whose content is map of structure Map<LocalDate, Map<String, List<FlexiServer>>>, and when I try to read this JSON file using object mapper into a map, it does not produce the map as expected.

Function to read JSON file

private Map<LocalDate, Map<String, List<FlexiServer>>> loadOnDailyBasis(String path)
        throws IOException {

        InputStream stream = this.getClass().getResourceAsStream(path);
        return JSON_MAPPER.readValue(stream, Map.class);
    }

Calling the function and loading it into a map called data

Map<LocalDate, Map<String, List<FlexiServer>>> data = loadOnDailyBasis(
            "/testdata/servers/dailyservers.json");

The data is a LinkedHashMap which has key as date and value is LinkedHashMap. The value which is the internal map has the key as string and value as ArrayList. Till here this is fine, but when I see the contents of this ArrayList, it is again a linked hash map, where the key is the name of the field and value is its value. This is wrong.

enter image description here

Kindly suggest how can I deserialize it properly.

Loui
  • 533
  • 17
  • 33
  • The example data seems to be more like ```Map>>```. I'm especially missig the ```ArrayList``` mentioned in your description. BTW: "does not produce ... as expected" could be more precise. Any Exceptions? What does it produce? – blafasel Mar 06 '20 at 11:47
  • actually I am able to solve this, let me post my answer – Loui Mar 06 '20 at 11:53

2 Answers2

0

So, after reading about Map serialization and de-serialization from here I found that we can use Type Reference to correctly map into the required data structure.

private Map<LocalDate, Map<String, List<FlexiServer>>> loadOnDailyBasis(String path)
        throws IOException {

        InputStream stream = this.getClass().getResourceAsStream(path);
        TypeReference<Map<LocalDate, Map<String, List<FlexiServer>>>> typeRef = new TypeReference<Map<LocalDate, Map<String, List<FlexiServer>>>>() {
        };
        return JSON_MAPPER.readValue(stream, typeRef);
    }
Loui
  • 533
  • 17
  • 33
0

I dont have the points to comment yet, but why use a nested map? Do you need the data structure? Why not create your own key.

private final LocalDate date;
private final String id;

public YourKey(LocalDate date, String id) {
    this.date = date;
    this.id = id;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof YourKey)) return false;
    YourKey yourKey = (YourKey) o;
    if (!date.equals(yourKey.date)) return false;
    return id.equals(yourKey.id);
}

@Override
public int hashCode() {
    int result = date.hashCode();
    result = 31 * result + id.hashCode();
    return result;
}

And then use Map<YourKey, List<FlexiServer>>. This Map should be serializable without problems.

magicmn
  • 1,787
  • 7
  • 15
  • Actually thats a better a idea, thanks for pointing this out, my bad that i missed it. – Loui Apr 24 '20 at 17:03