I have the JSON below:
{
"abc": {
"linkedTo": "count",
// possibly more data...
},
"plmtq": {
"linkedTo": "title",
"decode": "true",
// possibly more data...
}
}
I need to load this JSON into a Map<String, Holder>
, with keys "abc"
and "plmtq"
.
Below is my Holder
class:
public class Holder {
private final Map<String, String> data;
public Holder(Map<String, String> data) {
this.data = data;
}
// More methods in this class...
}
The JSON does not match my class structure, but I cannot change the JSON or the classes.
What I need is a way to customize the deserialization so I can parse the JSON into a Map<String, Holder>
.
Is there any way to do this?
Below is the code which does that, but it looks too complex and there must be a simpler way to do it...
private static Map<String, Holder> getMap(String jsonLine)
{
Map<String, Holder> holder = new HashMap<>();
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : jobject.entrySet())
{
Map<String, String> metadata = new HashMap<>();
JsonObject element = entry.getValue().getAsJsonObject();
for (Map.Entry<String, JsonElement> entry2 : element.entrySet())
{
metadata.put(entry2.getKey(), entry2.getValue().getAsString());
}
holder.put(entry.getKey(), new Holder(metadata));
}
return holder;
}