Creating a Java Object from JSON Object containing JSON Maps using GSON -
so, i've been doing gson while, ran issue of using json maps, understand key value pairs value json object.
to give idea i'm coming from, here's json
{ "configs":[ { "com.hp.sdn.adm.alert.impl.alertmanager":{ "trim.alert.age":{ "def_val":"14", "desc":"days alert remains in storage (1 - 31)", "val":"14" }, "trim.enabled":{ "def_val":"true", "desc":"allow trim operation (true/false)", "val":"true" }, "trim.frequency":{ "def_val":"24", "desc":"frequency in hours of trim operations (8 - 168)", "val":"24" } } }, { "com.hp.sdn.adm.auditlog.impl.auditlogmanager":{ "trim.auditlog.age":{ "def_val":"365", "desc":"days audit log remains in storage (31 - 1870)", "val":"365" }, "trim.enabled":{ "def_val":"true", "desc":"allow trim operation (true/false)", "val":"true" }, "trim.frequency":{ "def_val":"24", "desc":"frequency in hours of trim operations (8 - 168)", "val":"24" } } } ] }
all of com.hp.sdn... things dynamic, in won't know key names until runtime. figured can use hashmap , gson figure out, i'm not sure name field...
here classes have far
package com.wicomb.sdn.models.configs; import java.util.hashmap; import com.wicomb.sdn.types.model; public class configresponse extends model { private configgroup[] configs; }
package com.wicomb.sdn.models.configs; import com.wicomb.sdn.types.model; public class configgroup extends model { private hashmap<string,config> ????; }
tl;dr how should write java class let gson know how handle json property don't know name of.. , lots of them.
you can feed gson hashmap
(or if children order important linkedhashmap
) iterate on entries or keys other map.
in code below use following json input:
{ "test": 123, "nested":{ "nested-1": 1, "nested-2": 2 } }
and code looks these:
public void testgson() { string input = "{\"test\": 123, \"nested\": {\"nested-1\": 1, \"nested-2\": 2}}"; linkedhashmap<string, object> json = new gson().fromjson(input, linkedhashmap.class); // iterating for(map.entry<string, object> entry : json.entryset()){ system.out.println(entry.getkey() + " -> " + entry.getvalue()); } // testing values system.out.println(json.get("test")); // should 123 map<string, object> nested = (map<string, object>) json.get("nested"); system.out.println(nested.get("nested-1")); // should 1 system.out.println(nested.get("nested-2")); // should 2 }
Comments
Post a Comment