Handling a Json API response with java

I’ve been trying to figure out how to handle the json response from a GET request. This is the code I have for the request:

String urlString = URL I want to request;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    InputStream is = conn.getInputStream();
    String response = getStringFromInputStream(is);

My question is what to do now. I’ve been playing with gson but I cannot figure out how to parse the response for the required information.

I also found this method somewhere online to turn the response into a string:

 private static String getStringFromInputStream(InputStream is) {

    BufferedReader br = null;
    StringBuilder sb = new StringBuilder();

    String line;
    try {

        br = new BufferedReader(new InputStreamReader(is));
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return sb.toString();

}

If anyone could help me parse the string or somehow otherwise handle the response I’d really appreciate it.

Answer

You can use Jackson framework to parse the response into Java Object. Once you add the dependency, this is how it will work:

Let’s say you are getting the below response from the API:

{
    "id": 1,
    "name": "foo"
}

You can write the following code to deserialise it into an Object:

public class Response {
    private int id;
    private String name;
    //Getters and Setters
}

//code to convert
String response = sb.toString();
ObjectMapper mapper = new ObjectMapper();
Response responseObject = mapper.readValue(response, Response.class);

If the json is not valid, it will fail and throw JsonParseException or JsonMappingException. You can handle it in your code and respond accordingly.

Here’s step by step tutorial on how to use Jackson.

Leave a Reply

Your email address will not be published. Required fields are marked *