2017-04-24 111 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()); 
     }