使用GSON从JSON转换,无法将ArrayList转换为对象

时间:2018-07-19 15:11:03

标签: java android json gson

我试图通过将ArrayList转换为JSON来使用SharedPreferences保存数据。每当我尝试检索数据并将其转换回时,我都无法将ArrayList转换为播放列表错误。有什么想法可能是哪里错了吗?

我的播放列表课程:

public class Playlist extends ArrayList<Parcelable> implements Parcelable{
private ArrayList<Song> playlistSongs;
private String name;

public Playlist(String name) {
    this.name = name;
    this.playlistSongs = new ArrayList<>();
}

protected Playlist(Parcel in) {
    playlistSongs = in.createTypedArrayList(Song.CREATOR);
    name = in.readString();
}

public static final Creator<Playlist> CREATOR = new Creator<Playlist>() {
    @Override
    public Playlist createFromParcel(Parcel in) {
        return new Playlist(in);
    }

    @Override
    public Playlist[] newArray(int size) {
        return new Playlist[size];
    }
};

public ArrayList<Song> getPlaylistSongs() {
    return playlistSongs;
}

public String getName() {
    return name;
}

@Override
public String toString() {
    return name;
}

public int getCount(){
    return playlistSongs.size();
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeTypedList(playlistSongs);
    parcel.writeString(name);
}

@Override
public Stream<Parcelable> stream() {
    return null;
}

@Override
public Stream<Parcelable> parallelStream() {
    return null;
}

}

在活动中创建所有播放列表后调用的转换为JSON方法:

public boolean writeJSON(ArrayList<Playlist> playlists) {

    SharedPreferences mSettings = getSharedPreferences("Playlists", Context.MODE_PRIVATE);
    SharedPreferences.Editor mEditor = mSettings.edit();

    Type type = new TypeToken<ArrayList<Playlist>>() {
    }.getType();
    try {
        String writeValue = mGson.toJson(playlists, type);
        mEditor.putString("Playlists", writeValue);
        mEditor.commit();
        return true;
    } catch (Exception e) {
        return false;
    }
}

在用户重新启动应用程序后调用的读取的JSON方法:

    public ArrayList<Playlist> readJSON() {

    SharedPreferences mSettings = getSharedPreferences("Playlists", Context.MODE_PRIVATE);
    Type collectionType = new TypeToken<ArrayList<Playlist>>() {
    }.getType();
    String loadValue = mSettings.getString("Playlists", null);
    ArrayList<Playlist> temp = mGson.fromJson(loadValue, collectionType);
    return temp;
}

2 个答案:

答案 0 :(得分:1)

我认为问题在于Playlist类扩展了ArrayList。 GSON尝试将您的Playlist序列化为Parcelable的列表。从您的班级来看,似乎Playlist确实不需要扩展ArrayList。我尝试运行您的示例(为了减少到最低限度,我不得不删除很多内容),并且它将每个Playlist序列化为一个空列表(字符串"[]"),无论是什么。在playlistSongs中。我删除了超类,它开始按预期运行。

答案 1 :(得分:1)

我认为问题是此extends ArrayList<Parcelable>。尝试使其extends ArrayList<Song>,并且您也不需要保留对Arraylist(private ArrayList<Song> playlistSongs;)的引用