Search code examples
javajsonarraylistgetter-setter

Get to get data from arrayList in another class?


  /**
 * 5 points
 *
 * You will write a method that converts a JSON Object into a Song object. It should assume that the input is in the format:
 * {"title":"Lose Yourself", "artist":"Eminem", "ratings":[5,5,4,5], "youtubeID":"xFYQQPAOz7Y"}
 *
 * @param jsonSong  A song in JSON format
 * @return A Song object with the data from the JSON Value
 */
public static Song jsonToSong(JsonObject jsonSong){
    String title =jsonSong.get("title").asString();
    String YoutubeID =jsonSong.get("youtubeID").asString();
    String artist =jsonSong.get("artist").asString();



    ArrayList<Integer> ratings = new ArrayList<Integer>();

    Song object = new Song(YoutubeID,title,artist,ratings);
    object.setTitle(title);
    object.setArtist(artist);
    object.setRatings(ratings);
    object.setYoutubeID(YoutubeID);


    return object;

I've written this code which converts a JsonObject into a type Song Object, everything converts except for the arraylist (ratings).

How do I retrieve it's data correctly using getter and setter methods?

My getter setter methods are:

 public ArrayList<Integer> getRatings(){
    return ratings;
}

public void setRatings(ArrayList<Integer> ratings){
    this.ratings = ratings;
}

The constructor:

   // Constructor
public Song(String youtubeID, String title, String artist, ArrayList<Integer> ratings){
    this.youtubeID = youtubeID;
    this.title = title;
    this.artist = artist;
    this.ratings = ratings;
}

Over here you can see that everything converts except for rating when ran through the grader

    Incorrect on input: {"title":"Comfortably Numb","artist":"Pink Floyd","ratings":[5,4,5,5],"youtubeID":"_FrOQC-zEog"}
Expected output : {title:Comfortably Numb, artist:Pink Floyd, ratings:[5, 4, 5, 5], youtubeID:_FrOQC-zEog}
Your output     : {title:Comfortably Numb, artist:Pink Floyd, ratings:[], youtubeID:_FrOQC-zEog}
Score: 0

Solution

  •      ArrayList<Integer> ratings = new ArrayList<Integer>(); 
                JsonValue collect = jsonSong.get("ratings"); 
                JsonArray rate = collect.asArray();
                for(int i=0; i<rate.size(); i++){
                    ratings.add(rate.get(i).asInt());
                }