0

I have a response from API that generates authorization token with some other attributes, I'm trying to extract the value of the token from the response which looks like below

 {"access_token":"tokenvalue","scope":"somevalue","token_type":"Bearer","expires_in":value}

i tried JSON parse like below:

 Myclass response = template.postForObject(url, requestEntity,  Myclas.class);
            JSONParser jsonParser = new JSONParser();
        JSONObject obj = (JSONObject) jsonParser.parse(response);
        String product = (String) jsonObject.get("access_token");
            token = response;
        }

Recieved error:

parse( ) 
in JSONParser cannot be applied
to
(java.lang.String)
3
  • 1
    The json response is an invalid json. did u mask the expires_in or that's how is it? Commented May 7, 2018 at 14:37
  • check this link examples.javacodegeeks.com/core-java/json/… Commented May 7, 2018 at 14:49
  • @KarthikR this is the response: {"access_token":"tokenvalue","scope":"somevalue","token_type":"Bearer","expires_in":1235} Commented May 7, 2018 at 15:11

2 Answers 2

1

With the line:

String product = (String) jsonObject.get("access_token");

You are trying to get a property called "access_token".

However if you look at your json you will see that there is no property called "access_token".

Perhaps you meant:

String product = (String) jsonObject.get("token");
Sign up to request clarification or add additional context in comments.

Comments

0

Like said by Neng Liu before me, this JSON could be incorrect:

{"token":"tokenvalue","scope":"somevalue","token_type":"Bearer","expires_in": value }

Another thing is that JSONObject can receive the JSON format in its constructor JSONObject obj = new JSONObject(response) in your case and then use obj.get("your filed")

4 Comments

JSONObject json = (JSONObject)new JSONParser().parse("{\"access_token\":\"token\", \"scope\":value, \"token_type\":Bearer, \"expires_in\":97822}"); System.out.println("access_token=" + json.get("access_token")); Got this error: JSONParser() in JSONParser cannot be applied to:....i'm using jdk.nashorn
Sorry, but scope variable is a string?
@hellomluca, yes it's a string :)
So this json file is uncorrect. It must be like this: "{\"access_token\":\"token\", \"scope\": " value " , \"token_type\":Bearer, \"expires_in\":97822}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.