/**
* 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转换为类型的歌曲对象,除了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
不知道您使用的是什么JSON库,但是我想此jsonobject具有类似于方法getJsonArray((之类的东西,您可以尝试使用它使用它与类型JSONARRAY的对象,然后迭代它得到您想要的。
或类似的东西
JSONArray ratings= (JSONArray) jsonSong.get("ratings");
Iterator<Integer> iterator = ratings.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
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());
}