Return every song from the music ratings API as an ArrayList of Song objects. *
ID: 3823665 • Letter: R
Question
Return every song from the music ratings API as an ArrayList of Song objects.
*
* A JSON string containing the information for every rated song can be obtained with a GET
* request to the url: http://fury.cse.buffalo.edu/musicRatings/getAllSongs
* The format of the returned string is a JSON list of songs represented as JSON objects in the
* same format as the input of the previous method. To see this format and the data you can paste
* the url into a web browser.
*
* @return An ArrayList containing all the songs from the music ratings API
*/
public static ArrayList<Song> getAllSongsFromAPI() {
return null;
}
/**
* 10 points
*
* Returns the song from the music ratings API that has been rated the most number of times as
* a Song object. The rating of the songs should not be considered in this method, only the number
* of times they have been rated. Ties can be broken arbitrarily.
*
* @return A Song with the most reviews
*/
public static Song getMostRatedSong(){
return null;
}
Need the correct answer to these two questions I have been struggling with them for almost 2 weeks now.
Explanation / Answer
The below code will fetch the data from the URL. After which we have to map the List of Jsons into Java objects. For this we need to add dependency jars called Jackson. Since i cannot attact the jar, I am giving the hint of code piece to map the Json to Java Objects.
"JSONObject obj = (JSONObject) JSONValue.parse(str);"
After which you can easily write your logics to solve the problem.
http://stackoverflow.com/questions/33441153/how-to-get-a-specific-value-from-json-string
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class HelloWorld{
public static void main(String []args){
try{
System.out.println(sendGET());
}catch(Exception e){
e.printStackTrace();
}
}
private static String sendGET() throws Exception {
URL obj = new URL("http://fury.cse.buffalo.edu/musicRatings/getAllSongs");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
//con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
throw new Exception();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.