Skip to content

Instantly share code, notes, and snippets.

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 n2o/13227bbfc9d84f5a1554923356ebee31 to your computer and use it in GitHub Desktop.
Save n2o/13227bbfc9d84f5a1554923356ebee31 to your computer and use it in GitHub Desktop.
Professional Programming: Results of practical exercises, week 7

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'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment