com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期BEGIN_OBJECT但在第1行第2列是BEGIN_ARRAY

时间:2013-09-10 02:13:04

标签: java android android-asynctask gson

我想使用Gson库将学生名单从AsyncTask传递给Activity

但它给了我以下错误:

错误日志:

       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 Full 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();
}

}

这是ListView1 Activity方法,它应该从AsyncTask返回或获取该列表: 注意:我认为错误来自于此处的评论

 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;
}

我需要你帮助因为它是第一次使用Gson Library。

2 个答案:

答案 0 :(得分:5)

您序列化了Student个实例的列表,但您尝试从保存的字符串中反序列化单个Student。试试这个:

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);

答案 1 :(得分:0)

这可能有所帮助。而不是反序列化单个学生对象试试这个。

List<Student> expectedList =  new Gson()
                            .fromJson(prefs.getString("studentnames", null),
    new TypeToken<List<Student>>() {}.getType());