0
votes

I am trying to hit a API endpoint which is responding something like below when I am calling response.getBody()

{ "oktaToken": "eyJraWQiOiIyNlN1NHFMNnVVZTVJX2M5X2Z3WmZvX09ON0dNUHRtQzlEeHFsTGplLS00IiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULlVINmdIOF9BcWJ" }

Now I wanted to store the value of this token into a string variable.

response.getbody() is already a string but I want the value to be stored in a String variable. I don't wanted to do any manipulation in the String (response.getbody()) like splitting & substring.

Is there something using json parsing so That I can get the value of token in a variable by passing the key('oktaToken')?

2

2 Answers

0
votes
String jsonStr = '{ "oktaToken":"eyJraWQiOiIyNlN1NHFMNnVVZTVJX2M5X2Z3WmZvX09ON0dNUHRtQzlEeHFsTGplLS00IiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULlVINmdIOF9BcWJ" }';
Map<String, String> m = (Map<String, String>) JSON.deserialize(jsonStr, Map<String, String>.class);
String oktaToken = m.get('oktaToken');
System.debug(oktaToken);

Is this what you are looking for?

0
votes

JSON.parse(string) will use the input string to create an object, and it's properties can then be accessed using dot notation.

So in your case, you could do something like:

var responseBody = JSON.parse(response.getBody());
var oktaToken = responseBody.oktaToken;