I have JSON as such:
{
"Temperature": {
"Name": "Temperature",
"Value": "26.19",
"Unit": "C"
},
"Humidity": {
"Name": "Humidity",
"Value": "29.38%",
"Unit": "%"
}
}
and I want to save it into List of objects of same type. Here is my class:
public class Measurement {
private String name;
private String value;
private String unit;
public Measurement(String name, String value, String unit){
this.name = name;
this.value = value;
this.unit = unit;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public String getUnit() {
return unit;
}
@Override
public String toString(){
return name + " = " + value + unit;
}
}
I have tried it usng gson like this:
Type measurementListType = new TypeToken<ArrayList<Measurement>>(){}.getType();
List<Measurement> msm = new Gson().fromJson(json, measurementListType);
but that gives error
Expected BEGIN_ARRAY but was BEGIN_OBJECT
Provided JSON is just an example, it could have any number of objects, but they would all have to follow same structure. How can I parse them into List? Any help is greatly appreciated.
For that JSON you're showing to be an array of objects, it needs to be sorrounded by square brackets, like this:
[{
"Temperature": {
"Name": "Temperature",
"Value": "26.19",
"Unit": "C"
},
"Humidity": {
"Name": "Humidity",
"Value": "29.38%",
"Unit": "%"
}
}]
From there you can have one or multiple objects inside the array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.