0

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.

Jonathan Zier
  • 150
  • 2
  • 14
  • Are you interested in parsing it using a specific framework or are you just looking for options? – nortontgueno Jan 24 '19 at 17:50
  • What response are you getting? – Darshan Mehta Jan 24 '19 at 17:50
  • @ngueno the framework doesn't really matter to me – Jonathan Zier Jan 24 '19 at 17:53
  • @DarshanMehta I used a json validator to make sure that the response is Json in the right format – Jonathan Zier Jan 24 '19 at 17:54
  • Your `getStringFromInputStream` can be made much more concise and readable by using [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html). Also, there are various even shorter ways of reading an InputStream into a String discussed in [this SO question](https://stackoverflow.com/questions/309424/how-do-i-read-convert-an-inputstream-into-a-string-in-java). – DodgyCodeException Jan 24 '19 at 18:05

2 Answers2

2

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.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
2

It depends on the what you want to do with Json.I am assuming you want to convert in into an Java object. For that you can use Gson or Jackson. Suppose you have a json like

{"userId":"1","userName":"Yasir"}

and your java class like

class User{
int userId;
String userName;
//setters and getters
}

then you can use something like

Gson gson = new Gson();
User user= gson.fromJson(jsonInString, User.class);

to create java object.

Ratish Bansal
  • 1,982
  • 1
  • 10
  • 19