I have a nested JSON object in which one of the nested objects (keyed parameters) is an unknown object itself. The only known part is that it's an array of further objects.
The problem is that the contents of this object are completely unknown(dynamic) and so I can't define a class with some known variable names for it.
What I need to achieve is to extract and store all these dynamic key-value pairs. For example in the below code, for parameters I need to extract both alpha and then its contents type, and store them as a Map.
js is the JSON I'm trying to parse into my class NestedJsonParse.
public class NestedJsonParse {
String name;
Experiment experiment;
Parameters parameters;
NestedJsonParse(String name, Experiment experiment, Parameters parameters) {
this.name = name;
this.experiment = experiment;
this.parameters = parameters;
}
public String getName() { return name; }
public String getExpName() { return experiment.getName(); }
public String getParams() { return parameters.getParamsAsStrings(); }
@Override
public String toString() {
return "NSP{" +
"name='" + getName() + '\'' +
", exp-name='" + getExpName() + '\'' +
", params='" + getParams() + '\'' +
"========================================" +
"}";
}
public class Experiment {
String name;
Experiment(String name) {
this.name = name;
}
public String getName() { return name; }
}
public class Parameters {
List<JSONObject> parameters;
Parameters(List<JSONObject> parameters) {
this.parameters = parameters;
}
public String getParamsAsStrings() {
return "abc";
}
}
public static void main(String[] args) throws Exception {
String js = "{\"name\" : \"e0\", \"experiment\" : { \"name\" : \"e1\" }, \"parameters\" : [ {\"alpha \": { \"type\" : \"float\" } } ] }";
JSONParser parser = new JSONParser();
Object obj = parser.parse(js); // Passes
Gson GSON = new GsonBuilder().create();
NestedJsonParse nsp = GSON.fromJson(js, NestedJsonParse.class); // Fails
System.out.println("NSP : " + nsp.toString());
}
}
This passes if the JSON does not contain a parameters block but fails otherwise with this error:
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 206 path $.parameters