/**
* 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(评级)之外,所有内容都会转换。
如何使用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 :(得分:0)
不知道你使用的是什么Json库,但我想这个JsonObject有类似方法getJsonArray()的东西,你可以尝试使用它来获取类型为JsonArray的对象,然后迭代它并获得你想要的东西。 / p>
或类似的东西
JSONArray ratings= (JSONArray) jsonSong.get("ratings");
Iterator<Integer> iterator = ratings.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
答案 1 :(得分: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());
}