StrikeNeo
StrikeNeo

Reputation: 57

JSON Object extract value

I have this code that return a response from an API provider in the format of JSON Object. Below is the code:

public class Authentication {   
    public static void main(String[] args) {
        try {
            URL url = new URL ("https://xxxxx.com");
            String encoding = "xxxxxxxxx";
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            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();
        }
    }
}

The above code will return a response like this:

{
  "accessToken": "0.AQAAAUmdztB3AAAAAAAEkvg",
  "tokenType": "Bearer",
  "expiresIn": 300
}

So here is the problem, I'm trying to get the value of accessToken only so that i can use it to make an api call. I've tried this:

String loudScreaming = JSONML.toJSONObject("accessToken").getString("accessToken"); 

But it will return null. I've read about Jackson but don't have any idea on how to do it. Please guide me. Thanks in advance.

Upvotes: 0

Views: 1463

Answers (2)

Tim
Tim

Reputation: 43304

You don't need Jackson to parse a simple JSON structure. This will do the job

import org.json.JSONObject;

String jsondata = "{\"accessToken\":\"0.AQAAAUmdztB3AAAAAAAEkvg\",\"tokenType\":\"Bearer\",\"expiresIn\": 300}"

JSONObject obj = new JSONObject(jsondata);
String accessToken = obj.getJSONObject().getString("accessToken");

Upvotes: 1

mkobit
mkobit

Reputation: 47239

Here are a couple simple examples showing both how you could use Jackson (version 2.4.3) and how you could use GSON (version 2.3). These are pretty basic use cases and their documentation shows how versatile both of these libraries are.

final String JSON_STRING = "{\n" +
        "  \"accessToken\": \"0.AQAAAUmdztB3AAAAAAAEkvg\",\n" +
        "  \"tokenType\": \"Bearer\",\n" +
        "  \"expiresIn\": 300\n" +
        "}";
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode jackson = objectMapper.readValue(JSON_STRING, ObjectNode.class);
JsonNode jacksonAccessToken = jackson.get("accessToken");
System.out.println("Jackson accessToken: " + jacksonAccessToken);

Gson gson = new Gson();
JsonObject gsonObject = gson.fromJson(JSON_STRING, JsonObject.class);
JsonElement gsonAccessToken = gsonObject.get("accessToken");
System.out.println("GSON accessToken: " + jacksonAccessToken);

Upvotes: 0

Related Questions