5

我想使用 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

我的 AsyncTask 完整课程:

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

}

这是应该从 AsyncTask 返回或获取该列表的 ListView1 Activity 方法: 注意:我认为这里的错误在评论中引起

 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 。

4

2 回答 2

7

您序列化了一个实例列表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);
于 2013-09-10T05:24:00.827 回答
0

这可能会有所帮助。与其反序列化单个学生对象,不如试试这个。

List<Student> expectedList =  new Gson()
                            .fromJson(prefs.getString("studentnames", null),
    new TypeToken<List<Student>>() {}.getType());
于 2018-04-24T09:40:04.570 回答