Skip to content

Instantly share code, notes, and snippets.

@princessruthie
Created November 23, 2018 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save princessruthie/585932ba3a104f1bee7cbd19c3778316 to your computer and use it in GitHub Desktop.
Save princessruthie/585932ba3a104f1bee7cbd19c3778316 to your computer and use it in GitHub Desktop.
591 Gson practice
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class UrlPractice {
public static void main(String[] args) {
try {
URL url = new URL("http://www.recipepuppy.com/api/?q=turkey");
URLConnection con = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String response = "";
String inputLine;
while((inputLine = in.readLine()) != null) {
response+=inputLine;
System.out.println(inputLine);
}
in.close();
// System.out.println(response);
Gson gson = new Gson();
//get the outermost json object returned from api
JsonObject jobject = (JsonObject) new JsonParser().parse(response);
//get the json array called 'results'
JsonArray jarray = jobject.getAsJsonArray("results");
//a list to hold the recipes
ArrayList<RecipePuppyRecipe> recipes = new ArrayList<>();
//iterate over the json array, adding them to the list
//there's gotta be a better way, but here's *a way*
for(JsonElement o: jarray) {
recipes.add(gson.fromJson(o, RecipePuppyRecipe.class));
}
//if you want to look at the list, this is a good breakpoint
System.out.println("here's an example of one of the recipes: " + recipes.get(0).title);
} catch(IOException e) {
System.out.println("The url wasn't able to open");
}
}
public class RecipePuppyRecipe {
String title;
String url;
String ingredients;
String imageSource;
public RecipePuppyRecipe(String title, String url, String ingredients, String imageSource) {
super();
this.title = title;
this.url = url;
this.ingredients = ingredients;
this.imageSource = imageSource;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getIngredients() {
return ingredients;
}
public void setIngredients(String ingredients) {
this.ingredients = ingredients;
}
public String getImageSource() {
return imageSource;
}
public void setImageSource(String imageSource) {
this.imageSource = imageSource;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment