Java – com.google.gson.JsonSyntaxException : java. lang. IllegalStateException: Should be BEGIN_ARRAY but STRING

com.google.gson.JsonSyntaxException : java. lang. IllegalStateException: Should be BEGIN_ARRAY but STRING… here is a solution to the problem.

com.google.gson.JsonSyntaxException : java. lang. IllegalStateException: Should be BEGIN_ARRAY but STRING

This is my first method of serialization using gson. I get a Facebook response to my Android app like this

My Jason:

 {"data": [
    {
        "pic_square": "https://fbcdn-profile-a.akamaihd.netxxxx1388091435_797626998_q.jpg",
        "uid": "10202xxx852765",
        "name": "Mister X"
    },
    {
        "pic_square": "https://fbcdn-profile-a.akamaihd.netxxxx1388091435_797626998_q.jpg",
        "uid": "10202xxx852765",
        "name": "Mister X"
    }
   ]
}

try {
       final GsonBuilder builder = new GsonBuilder();
       final Gson gson = builder.create();
       JSONObject data= response.getGraphObject().getInnerJSONObject();             
       FacebookResponses facebookResponses= gson.fromJson(data.toString(),FacebookResponses.class); exception here
       Log.i(TAG, "Result: " + facebookResponses.toString());
    } catch (JsonSyntaxException e) {
        e.printStackTrace();

}
My class

public class FacebookResponses implements Serializable {
  private static final long serialVersionUID = 1L;
      @SerializedName("data");
      private FacebookRisp[] data;
}

class FacebookRisp implements Serializable {

private static final long serialVersionUID = 1L;

@SerializedName("pic_square")
   private String[] pic_square;

@SerializedName("uid")
   private String[] uid;

@SerializedName("name")
   private String[] name;

public String[] getPic_square() {
        return pic_square;
   }

public void setPic_square(String[] pic_square) {
    this.pic_square = pic_square;
   }

public String[] getUid() {
    return uid;
   }

public void setUid(String[] uid) {
    this.uid = uid;
   }

public String[] getName() {
    return name;
   }

public void setName(String[] name) {
    this.name = name;
   }

}

I understand.
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Should be BEGIN_ARRAY but column 118 in line 1 is STRING

Update:
I modified aegean’s answer and the question is []

@SerializedName("pic_square")
private String**[]** pic_square;   ex here and others

Solution

Change your FacebookResponses class to:

private class FacebookResponses {
    private Data[] data;
}

private class Data {
    @SerializedName("pic_square")
    private String picSquare;
    private String uid;
    private String name;
}

EDIT: Because the structure of your JSON response is as follows:

enter image description here

Related Problems and Solutions

Java – com.google.gson.JsonSyntaxException : java. lang. IllegalStateException: Should be BEGIN_OBJECT but column 2 in line 1 is BEGIN_ARRAY

com.google.gson.JsonSyntaxException : java. lang. IllegalStateException: Should be BEGIN_OBJECT but column 2 in line 1 is BEGIN_ARRAY… here is a solution to the problem.

com.google.gson.JsonSyntaxException : java. lang. IllegalStateException: Should be BEGIN_OBJECT but column 2 in line 1 is BEGIN_ARRAY

I want to use the gson library to pass a list of students from AsyncTask to an Activity as a list

But it gives me the following error :

Error log:

       FATAL EXCEPTION: main
   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hesham.sams/com.hesham.sams.ListActivity1}: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
    at android.app.ActivityThread.access$700(ActivityThread.java:140)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4921)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
    at dalvik.system.NativeStart.main(Native Method)
   Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
    at com.google.gson.Gson.fromJson(Gson.java:803)
    at com.google.gson.Gson.fromJson(Gson.java:768)
    at com.google.gson.Gson.fromJson(Gson.java:717)
    at com.google.gson.Gson.fromJson(Gson.java:689)
    at com.hesham.sams.ListActivity1.getNames(ListActivity1.java:171)
    at com.hesham.sams.ListActivity1.onCreate(ListActivity1.java:68)
    at android.app.Activity.performCreate(Activity.java:5206)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
    ... 11 more
   Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
    at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:374)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
    ... 20 more

My AsyncTask complete class:

public class GetListAsync extends AsyncTask<Void, Void, ArrayList<Student>> {

private Activity activity;
private  ProgressDialog progressDialog;
 Context context;

public GetListAsync(Activity activity, ProgressDialog progressDialog, Context context) {
    super();
    this.progressDialog = progressDialog;
    this.activity = activity;
    this.context = context;
}
 private Student get(String s) {

return new Student(s);

}

@Override
protected ArrayList<Student> doInBackground(Void... voids) {

ArrayList<Student> StudentIdList = new ArrayList<Student>();
    ArrayList<Student> StudentNamesList = new ArrayList<Student>();

SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);
    String TID = prefs.getString("TID", null);
 SoapObject request2 = new SoapObject(NAMESPACE2, METHOD_NAME2);
        PropertyInfo pi2 = new PropertyInfo();
        pi2.setName("TID");
        pi2.setValue(Integer.parseInt(TID.toString()));
        pi2.setType(Integer.class);
        request2.addProperty(pi2);
        SoapSerializationEnvelope envelope2 = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope2.setOutputSoapObject(request2);
        HttpTransportSE androidHttpTransport2 = new HttpTransportSE(URL2);

try {

androidHttpTransport2.call(SOAP_ACTION2, envelope2);

KvmSerializable result = (KvmSerializable) envelope2.bodyIn;

String str = null;
            for (int i = 0; i < result.getPropertyCount(); i++) {
                str = ((String) result.getProperty(i).toString());

StudentIdList.add(get(str));

}
            return StudentIdList;
        } catch (Exception e) {

}

return  StudentIdList;
}

@Override
protected void onPostExecute(ArrayList<Student> result) {

GsonBuilder gsonb = new GsonBuilder();
    Gson gson = gsonb.create();
    String json = gson.toJson(result);
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);
    prefs.edit().putString("studentnames", json).commit();

activity.startActivity(new Intent(activity, ListActivity1.class));

progressDialog.dismiss();
}

}

This is the ListView1 activity method, which should return or get the list from AsyncTask:
Note: I think the error was caused from here in the comments

 public List<Student> getNames() {
SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());

Gson gson = new Gson();
    String result = prefs.getString("studentnames", null);

Student obj = gson.fromJson(result, Student.class);  MayBe the error   here in class type 

Toast.makeText(getApplicationContext(), obj.toString(),
            Toast.LENGTH_LONG).show();
return (List<Student>) obj;
}

I need your help because this is the first time using the gson library.

Solution

You serialized a list of Student instances, but you tried to deserialize a single Student from a saved string. Try this :

Gson gson = new Gson();
String result = prefs.getString("studentnames", null);

ArrayList<Student> list = new ArrayList<Student>();
Type listType = new TypeToken<List<Student>>() {}.getType();
list = gson.fromJson(result, listType);

Related Problems and Solutions