使用Gson序列化具有非原始值的对象的ArrayList吗?

问题描述 投票:0回答:1

所以我有这个课

public class Place {

    ArrayList<Stop> stops;
    String name;
    Location location;

    public Place(String name, Location location){
        this.name = name;
        this.location = location;
    }

    public void addStop(Stop stop){
        this.stops.add(stop);
    }

    public Location getLocation() {
        return location;
    }

    public String toString(){
        return name+ " : " +location.toString();
    }
}

我用于Android项目。每个Place对象都有一个Location对象(来自Google Play服务),应用程序有一个ArrayList items arraylist,用于存储用户输入的数据。我正在使用Gson序列化该ArrayList并将其保存到SharedPrefs,但是当我还原数据时,Location对象的所有参数都显示为[[null。这是我的代码:

//If user has defined places, load them from storage mPrefs = getActivity().getPreferences(MODE_PRIVATE); Gson gson = new Gson(); String json = mPrefs.getString("user_places", ""); Type placeListType = new TypeToken<ArrayList<Place>>(){}.getType(); if(json.length() > 0) items = gson.fromJson(json, placeListType); else items = new ArrayList<Place>(); ... //Saves user data for future use SharedPreferences.Editor prefsEditor = mPrefs.edit(); Gson gson = new Gson(); String json = gson.toJson(items); prefsEditor.putString("user_places", json); prefsEditor.apply();
我在做什么错?如何确定原始的Location对象已正确还原?
java android serialization gson sharedpreferences
1个回答
0
投票
如果我正确理解了您的问题,可能是因为您正在从2个不同的活动中加载并保存您的Json字符串。
© www.soinside.com 2019 - 2024. All rights reserved.