预期为BEGIN_ARRAY,但为BEGIN_OBJECT | ArrayList问题 [英] Expected BEGIN_ARRAY but was BEGIN_OBJECT | ArrayList issue

查看:72
本文介绍了预期为BEGIN_ARRAY,但为BEGIN_OBJECT | ArrayList问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Gson库保存和检索Players对象的ArrayList.

I'm using the Gson library to save and retrieve an ArrayList of Players Objects.

@Override
protected void onStop() {
    super.onStop();
    SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();

    String guardJSON = gson.toJson(playersNoGuard);
    editor.putString(GUARD, guardJSON);

    editor.putString("lastActivity", getClass().getName());
    editor.apply();
}

我的onCreate重要部分

ArrayList<Player> playersNoGuard;
RecyclerView myList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_players_guard);

    SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
    String guardJSON = prefs.getString(GUARD, null);
    Type arrayListPlayers = new TypeToken<ArrayList<Player>>(){}.getType();
    Gson gson = new Gson();

    if(guardJSON != null) {
        playersNoGuard = gson.fromJson(guardJSON, arrayListPlayers);
    }

    // Get the players and remove the Clairvoyant
    Intent intent = this.getIntent();
    playersNoGuard = intent.getParcelableArrayListExtra("PLAYERS");

    [...] // Code skipped

    }


但是当运行此活动时,我得到以下错误日志:


But when this Activity is run, I get the following error log:

由以下原因引起:java.lang.IllegalStateException:预期为BEGIN_ARRAY,但在第1行第2列$$处为BEGIN_OBJECT

Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

此代码有什么问题?

推荐答案

您可能在其他地方写了相同的首选项条目.确保您的密钥(GUARD)在整个应用程序中是唯一的.

You probably write to the same preferences entry somewhere else. Ensure that your key (GUARD) is unique throughout the application.

这篇关于预期为BEGIN_ARRAY,但为BEGIN_OBJECT | ArrayList问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆