I'm tryin to use Sharedpreferences to save an arraylist of objects, but toJson and fromJson are causing fatal exceptions

前端 未结 2 1228
时光说笑
时光说笑 2021-01-16 09:01

My object contains a String, long, and int. Object is called Tracker and I have an arrayList of Trackers. When I try to use toJson i get an error. The same with fromJson.

2条回答
  •  囚心锁ツ
    2021-01-16 09:21

    It looks like you're trying to convert a list to json as an object instead of a list. You could just create a wrapper class to hold your list and serialize/deserialize that.

    Create a simple class that acts as a wrapper for your List.

    class TrackWrapper {
        List trackList;
    
        public TrackWrapper(List tracks){
            this.trackList = tracks;
        }
    }
    

    Add items to the list

    Tracker trax = new Tracker(description, timeToCount, imageID);
    track.add(trax);
    

    Create an instance of your wrapper class and pass your list in

    TrackWrapper wrapper = new TrackWrapper(trax);
    

    Serialise the wrapper

    Gson gson = new Gson();
    String json = gson.toJson(wrapper);
    

提交回复
热议问题