Last active
June 19, 2018 00:22
-
-
Save mithuns/668d5f15eafe2a0f8ba73f0783225cb3 to your computer and use it in GitHub Desktop.
Gson parsing sample code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ms; | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.lang.reflect.Type; | |
import java.net.HttpURLConnection; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.List; | |
import com.google.gson.Gson; | |
import com.google.gson.GsonBuilder; | |
import com.google.gson.JsonArray; | |
import com.google.gson.JsonDeserializationContext; | |
import com.google.gson.JsonDeserializer; | |
import com.google.gson.JsonElement; | |
import com.google.gson.JsonObject; | |
import com.google.gson.JsonParseException; | |
import com.google.gson.JsonParser; | |
public class Solution { | |
final static Gson gson = new GsonBuilder().setPrettyPrinting().setLenient().registerTypeAdapter(ServerResponse.class, new ServerResponse.Deserializer()).create(); | |
public static String[] getMovieTitles(String substr) throws IOException { | |
List<String> results = new ArrayList<>(); | |
int pageCount = getPageCount(substr); | |
if (pageCount == 0) { | |
return new String[0]; | |
} | |
for (int i = 1; i <= pageCount; i++) { | |
results.addAll(getData(substr, i)); | |
} | |
// sort the list once the list has all the results added so we only sort once. | |
Collections.sort(results, new Comparator<String>() { | |
@Override | |
public int compare(String o1, String o2) { | |
return o1.compareTo(o2); | |
} | |
}); | |
return results.toArray(new String[results.size()]); | |
} | |
/** | |
* This returns list of movie titles queried by the substr and the page number. | |
* | |
* @param substr | |
* @param pageCount | |
* @return | |
* @throws IOException | |
*/ | |
static List<String> getData(String substr, int pageNumber) throws IOException { | |
String serverReply = makeServerCall(substr, pageNumber); | |
ServerResponse response = gson.fromJson(serverReply, ServerResponse.class); | |
List<String> results = new ArrayList<>(); | |
for (MovieInfo movie : response.getData()) { | |
results.add(movie.title); | |
} | |
return results; | |
} | |
static int getPageCount(String substr) throws IOException { | |
String serverReply = makeServerCall(substr, 0); | |
ServerResponse response = gson.fromJson(serverReply, ServerResponse.class); | |
return response.totalPages; | |
} | |
/* | |
* The heart of this class, makes the server call and retrieves json string as server reply. | |
*/ | |
static String makeServerCall(String substr, int pageNo) throws IOException{ | |
URL url; | |
if(pageNo>=1) { | |
url= new URL("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr + "&page="+pageNo); | |
}else{ | |
url= new URL("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr); | |
} | |
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); | |
conn.setRequestMethod("GET"); | |
conn.setRequestProperty("Accept", "application/json"); | |
if (conn.getResponseCode() != 200) { | |
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); | |
} | |
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); | |
String temp; | |
StringBuffer output = new StringBuffer(); | |
while ((temp = br.readLine()) !=null ) { | |
output.append(temp); | |
} | |
return output.toString(); | |
} | |
static class MovieInfo { | |
private String posterUrl; | |
private String title; | |
private int year; | |
private String type; | |
private String imdbId; | |
public MovieInfo(String posterUrl, String title, int year, String type, String imdbId) { | |
this.posterUrl = posterUrl; | |
this.title = title; | |
this.year = year; | |
this.type = type; | |
this.imdbId = imdbId; | |
} | |
public String getPosterUrl() { | |
return posterUrl; | |
} | |
public void setPosterUrl(String posterUrl) { | |
this.posterUrl = posterUrl; | |
} | |
public String getTitle() { | |
return title; | |
} | |
public void setTitle(String title) { | |
this.title = title; | |
} | |
public int getYear() { | |
return year; | |
} | |
public void setYear(int year) { | |
this.year = year; | |
} | |
public String getType() { | |
return type; | |
} | |
public void setType(String type) { | |
this.type = type; | |
} | |
public String getImdbId() { | |
return imdbId; | |
} | |
public void setImdbId(String imdbId) { | |
this.imdbId = imdbId; | |
} | |
} | |
static class ServerResponse { | |
private int page; | |
private int perPage; | |
private int total; | |
private int totalPages; | |
private List<MovieInfo> data; | |
public ServerResponse(int page, int perPage, int total, int totalPages, List<MovieInfo> data) { | |
this.page = page; | |
this.perPage = perPage; | |
this.total = total; | |
this.totalPages = totalPages; | |
this.data = data; | |
} | |
public int getPage() { | |
return page; | |
} | |
public void setPage(int page) { | |
this.page = page; | |
} | |
public int getPerPage() { | |
return perPage; | |
} | |
public void setPerPage(int perPage) { | |
this.perPage = perPage; | |
} | |
public int getTotal() { | |
return total; | |
} | |
public void setTotal(int total) { | |
this.total = total; | |
} | |
public int getTotalPages() { | |
return totalPages; | |
} | |
public void setTotalPages(int totalPages) { | |
this.totalPages = totalPages; | |
} | |
public List<MovieInfo> getData() { | |
return data; | |
} | |
public void setData(List<MovieInfo> data) { | |
this.data = data; | |
} | |
static final class Deserializer implements JsonDeserializer<ServerResponse> { | |
/** | |
* {@inheritDoc} | |
*/ | |
@Override | |
public ServerResponse deserialize(final JsonElement json, final Type typeOfT, | |
final JsonDeserializationContext context) throws JsonParseException { | |
final JsonObject jObject = json.getAsJsonObject(); | |
final int page = jObject.get("page").getAsInt(); | |
final int perPage = jObject.get("per_page").getAsInt(); | |
final int total = jObject.get("total").getAsInt(); | |
final int totalPages = jObject.get("total_pages").getAsInt(); | |
final JsonArray jsonArray = jObject.get("data").getAsJsonArray(); | |
final List<MovieInfo> movieList = new ArrayList<>(); | |
for (int i = 0; i < jsonArray.size(); i++) { | |
final JsonObject movieJson = jsonArray.get(i).getAsJsonObject(); | |
final String imdbId = movieJson.get("imdbID").getAsString(); | |
final String title = movieJson.get("Title").getAsString(); | |
final int year = movieJson.get("Year").getAsInt(); | |
final String posterUrl = movieJson.get("Poster").getAsString(); | |
final String type = movieJson.get("Type").getAsString(); | |
final MovieInfo MovieInfo = new MovieInfo(imdbId, title, year, posterUrl, type); | |
movieList.add(MovieInfo); | |
} | |
return new ServerResponse(page, perPage, total, totalPages, movieList); | |
} | |
} | |
} | |
public static void main(String[] args) { | |
try { | |
String[] sortedMovieTitles = getMovieTitles("spiderman"); | |
for(String str:sortedMovieTitles) { | |
System.out.println(str); | |
} | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} | |
//output | |
//Amazing Spiderman Syndrome | |
//Fighting, Flying and Driving: The Stunts of Spiderman 3 | |
//Hollywood's Master Storytellers: Spiderman Live | |
//Italian Spiderman | |
//Spiderman | |
//Spiderman | |
//Spiderman 5 | |
//Spiderman and Grandma | |
//Spiderman in Cannes | |
//Superman, Spiderman or Batman | |
//The Amazing Spiderman T4 Premiere Special | |
//The Death of Spiderman | |
//They Call Me Spiderman |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment