0

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; }
}
YHStan
  • 227
  • 3
  • 12
  • Can please you add the POJO you made and the complete JSON? – Most Noble Rabbit May 19 '21 at 09:22
  • 2
    Your type shouldn't be classname but a Collection of class name. Answered here: https://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type – Yayotrón May 19 '21 at 09:27
  • 1
    @Yayotrón Much thanks! This is what solved the problem I was facing! – YHStan May 19 '21 at 09:35
  • @CaffeineCoder Much thanks! I noticed a small trick that was in the comments of the link you sent where they recommended classname[].class which also seems to work for my problem! – YHStan May 19 '21 at 09:36

0 Answers0