I have the following json:
[
{
"type": 1,
"Steps": {
"steps": steps
}
},
{
"type": 2,
"HeartRate": {
"heartrates": heartRates
}
}
]
The field steps is just an int an heartRates is an array of int's. I want to parse this using gson to two classes. I found a similar question on stackoverflow: How parse json array with multiple objects by gson? and tried it but it didn't work. This is my code:
public class DataModels extends ArrayList<DataModels.Container> {
public class Container {
public int type;
public Object object;
}
public class Steps {
double steps;
public Steps(double steps) {
this.steps = steps;
}
public double getSteps() {
return steps;
}
@Override
public String toString() {
return "Steps: " + steps;
}
}
public class HeartRate {
int heartRate;
public HeartRate(int hr) {
heartRate = hr;
}
public double getHeartRate() {
return heartRate;
}
@Override
public String toString() {
return "Heart rate: " + heartRate;
}
}
}
Then for parsing my json:
public String getJSONMessage(String gearSData) {
System.out.println(gearSData);
Gson gson = new Gson();
DataModels model = gson.fromJson(gearSData, DataModels.class);
System.out.println(model);
for (DataModels.Container container: model) {
System.out.println(container.type);
System.out.println(container.object);
String innerJson = gson.toJson(container.object);
System.out.println("InnerJson: " + innerJson);
switch (container.type) {
case 1:
DataModels.Steps steps = gson.fromJson(innerJson, DataModels.Steps.class);
System.out.println(steps);
break;
case 2:
DataModels.HeartRate heartRate = gson.fromJson(innerJson, DataModels.HeartRate.class);
System.out.println(heartRate);
break;
}
}
}
The type gets parsed correctly but the innerjson is null and I don't know why. Can somebody explain this or does someone know a better way to do this?