In my code, I make a connection to a url and it returns an array of JSON objects as a String. Where ...... shows more JSON objects (random number of them). Currently, I am using a test sample link, thus the String only contains one item in array for example:
String str = [{sid:"somedat", data: [{otherdata: "etc"}, ......], cid: "somedat" }, ......]
//in actual code i would be calling the url here and assigning the returned string to the str variable
String samplestr = [{sid:"somedat", data: [{otherdata: "etc"}], cid: "somedat" }] //test sample
I would like to be able to convert this into an array of Java objects so i can process the data column inside before I insert to a mysql database. How should I proceed with gson? I was previously using the following for my previous JSON Object, but it doesnt really work for this example.
Gson gson = new Gson();
classname reply = gson.fromJson(str, classname.class);
This was the error message I got:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
Which doesnt make sense, since inside the java class i made (i think this was called POJO?), the data is stored in a private JsonArray variable. The java class i made is as follows:
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class getCurrentValuesSummaryReply {
private final String cid;
private final JsonArray data;
private final String sid;
public getCurrentValuesSummaryReply(String cid, JsonArray data, String sid){
this.cid = cid;
this.data = data;
this.sid = sid;
}
public void getValues(){
for (JsonElement datael : this.data){ //technically one item
JsonObject dataobj = datael.getAsJsonObject();
for (Object key: dataobj.keySet()){
String keystr = key.toString();
System.out.println(this.cid+", "+keystr+", "+dataobj.get(keystr)+", "+this.sid);
}
}
}
public String getSid() { return this.sid; }
public JsonArray getData() { return this.data; }
public String getCid() { return this.cid; }
}