-6

I have rest call and I want to get one of the key values from the JSON response, for example the value of "employeeID".

This is the code for the rest call:



import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;



public class App {

public static String username = "Test_Username";

    public static void main(String[] args) {
        

        try {
            URL url = new URL ("http://api.com/" + username);
            String encoding = Base64.getEncoder().encodeToString(":".getBytes("utf-8"));

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setRequestProperty  ("Authorization", "Basic " + encoding);
            InputStream content = (InputStream)connection.getInputStream();
            BufferedReader in   = 
                new BufferedReader (new InputStreamReader (content));   
         String line = "";
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } catch(Exception e) {
           e.printStackTrace();
        }
    }
}

And this is a sample of the JSON response:

[{
    "user": {
        "userID": "Adam555",
        "name": "Test Account",
        "id": 1055287,
        "recentApps": null,
        "employeeID": "2991KDS"
    },
    "user_state": {
        "EmployeeLookUpDBId": 1055304,
        "userID": "Adam555",
        "username": "Adam555"}]

So how can I get it in System.out.println for example saying "2991KDS"?

  • Doesn't this solve your problem? [https://stackoverflow.com/questions/10500775/parse-json-from-httpurlconnection-object](https://stackoverflow.com/questions/10500775/parse-json-from-httpurlconnection-object) – crocarneiro Aug 11 '21 at 19:32
  • @crocarneiro unfortunately no, I want to get a single value only, not the whole JSON response. I already get the response successfully, I just want to extract a single value from the response. – Adam Ayman Aug 11 '21 at 19:39
  • @AdamAyman After you parse the JSON response it is very easy to extract any value from the JSON response. Please search on google "How to use JSON response in Java" instead of posting on StackOverflow. – attempt0 Aug 12 '21 at 07:04

1 Answers1

0

Import this library your pom.xml file

`<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20200518</version>
</dependency>
`

`
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import org.json.JSONObject;
import org.json.JSONTokener;

public class App {

  public static String username = "Test_Username";

  public static void main(String[] args) {


    try {
      URL url = new URL ("http://api.com/" + username );
      String encoding = Base64.getEncoder().encodeToString(":".getBytes("utf-8"));

      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("GET");
      connection.setDoOutput(true);
      connection.setRequestProperty  ("Authorization", "Basic " + encoding);
      InputStream content = (InputStream)connection.getInputStream();
      JSONTokener tokener = new JSONTokener(content);
      JSONObject json = new JSONObject(tokener);

        System.out.println(json.getJSONObject("user").get("employeeID"));

    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}
`
Denis Kisina
  • 350
  • 4
  • 19
  • Thanks a lot it's getting close, I have now only small issue it's throwing an error because the JSON response starts with [{ I tried to replace [ with "" but no luck so far. @Chabo – Adam Ayman Aug 11 '21 at 20:14
  • @AdamAyman what is the structure of your JSON? Because that will determine how we access the fields. – Denis Kisina Aug 11 '21 at 20:17
  • @AdamAyman check my update. `{ "user": { "userID": "Adam555", "name": "Test Account", "id": 1055287, "recentApps": null, "employeeID": "2991KDS" }, "user_state": { "EmployeeLookUpDBId": 1055304, "userID": "Adam555", "username": "Adam555"} }` – Denis Kisina Aug 11 '21 at 20:29
  • This is my structure it's starting with [ which is causing the problem `[{ "user": { "userID": "Adam555", "name": "Test Account", "id": 1055287, "recentApps": null, "employeeID": "2991KDS" }, "user_state": { "EmployeeLookUpDBId": 1055304, "userID": "Adam555", "username": "Adam555"}]` – Adam Ayman Aug 11 '21 at 20:29
  • @AdamAyman That is not a valid JSON format – Denis Kisina Aug 11 '21 at 20:31
  • unfortunately this is how the response is coming and I cannot change it. Isn't it possible to replace the [ with nothing before ` JSONTokener tokener = new JSONTokener(content);` ? – Adam Ayman Aug 11 '21 at 20:34
  • Try replace method on String JSON before parsing it .replace("[", "").replace("]", "") – Denis Kisina Aug 11 '21 at 20:55
  • I tried below but didn't help or am I doing it wrong? `JSONTokener tokener = new JSONTokener(content).replace("[", "").replace("]", "");` – Adam Ayman Aug 11 '21 at 21:05
  • JSONObject json = new JSONObject( new JSONObject(tokener).toString() .replace("[", "") .replace("]", "")); – Denis Kisina Aug 11 '21 at 21:12
  • Same error "JSONObject text must begin with '{' – Adam Ayman Aug 11 '21 at 21:26