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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18709730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:22:45  来源:igfitidea点击:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2

javaandroidandroid-asynctaskgson

提问by hesham

i wanna to pass List of Student as List from AsyncTask to Activity using Gson library

我想使用 Gson 库将学生列表作为列表从 AsyncTask 传递到 Activity

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.access0(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 :

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

}

Here is ListView1 Activity method that's should return or get that list from AsyncTask: Note : I think the error cused from here in comment

这是应该从 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;
}

I need you help cuz it's first time to use Gson Library .

我需要你的帮助,因为这是第一次使用 Gson 库。

回答by giampaolo

You serialized a listof Studentinstances but you try to deserialize a single Studentfrom your saved string. Try this instead:

您序列化了一个实例列表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);

回答by TanvirChowdhury

This may help.Instead of deserializing a single student object try this.

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

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