2017-04-24 118 views
0
/** 
* 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; 

我已經編寫了將JsonObject轉換爲類型Song對象的代碼,除了arraylist(ratings)以外,所有內容都進行了轉換。獲取從另一個類arrayList中獲取數據?

如何使用getter和setter方法正確檢索數據?

我的getter setter方法是:

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

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

構造:

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

在這裏,你可以看到這一切轉變,除了等級,當通過分級機

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 
+0

有什麼相同的數據傳遞到您的構造函數和setter的意義呢?你的問題到底是什麼? – shmosel

+0

我需要使用來自arraylist評分的數據,這些數據看起來像這樣[5,6,5]放入SongObject評分中。 – Gintoki

回答

0
 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()); 
      } 
0

跑不知道你使用的是什麼Json庫,但我猜這個JsonObject有類似我的東西thod getJsonArray(),你可以嘗試使用它來獲取一個JsonArray類型的對象,然後迭代它並得到你想要的。

或者像這樣

 JSONArray ratings= (JSONArray) jsonSong.get("ratings"); 
     Iterator<Integer> iterator = ratings.iterator(); 
     while (iterator.hasNext()) { 
      System.out.println(iterator.next()); 
     }