I have this JSON
{"A":"valA",
"B":["valB"],
"C":"valC",
"D":"valD",
"data":[{
"data1":"dval1",
"data2":"dval2",
"data3":"dval3",
"data4":"dval4",}],
"F":"valF"}
Java Object:
public class ABCDObject {
private String A;
private String B;
private String C;
private String D;
private List<String> data = new ArrayList<String>(){
{
add("data1");
add("data2");
add("data3");
add("data4");
}
};
private String F;
//getters for the above A,B,C,D, and F
public List<String> getData() {
return data;
}
Main class
Gson gson = new Gson();
ABCDObject abcdObj = gson.fromJson(response, ABCDObject.class);
I am trying to access value of C as
abcdObj.getC();
I am getting the error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 9 column 17
Another question is how to access the value of data–> data1 and so on
The JSON doesn’t match the object, including:
Bis an array in the JSON, and a String inABCDObjectdatais an array of objects with four properties in the JSON, and an array of strings inABCDObject.Edit with example
Using the following two classes, and fixing the mal-formed JSON (the spurious comma after data4), this works as expected.
Data – holds each element of the “data” array, each data object has four data fields.
JsonHolder – encapsulates the entire JSON object.
sanity check
output
Note that attempting to work around the malformed JSON by using
JsonReader.setLenient(true)won’t work in this case; it only handles extra commas at the end of an array (collection), not in an object itself as your example JSON contains.