Today, we played around with Unirest, gson and a sample API to address our requests to. This is just a simple and small example, because we had not much time to live-code this problem.
import com.google.gson.Gson;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import java.util.List;
class Person {
String name;
int height;
List<String> starships;
}
class Starship {
String name;
}
public class App {
private static String getJsonString(String url) throws UnirestException {
HttpResponse<JsonNode> jsonNodeHttpResponse = Unirest.get(url).asJson();
return jsonNodeHttpResponse.getBody().toString();
}
private static void convertToJavaObject() throws UnirestException {
Gson gson = new Gson();
String darthVader = getJsonString("http://swapi.co/api/people/4/?format=json");
Person darthVaderObject = gson.fromJson(darthVader, Person.class);
String urlToStarhip = darthVaderObject.starships.get(0);
String jsonStarship = getJsonString(urlToStarhip);
Starship tie = gson.fromJson(jsonStarship, Starship.class);
System.out.println(tie.name);
}
public static void main(String[] args) {
try {
convertToJavaObject();
} catch (UnirestException e) {
e.printStackTrace();
}
}
}
Additional Gradle-dependencies:
dependencies {
compile 'com.mashape.unirest:unirest-java:1.4.9'
compile 'com.google.code.gson:gson:2.8.1'
}