Search code examples
salesforceapexapex-codesalesforce-lightningaura-framework

Apex (Salesforce) read json from response and store it in a string variable


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')?


Solution

  • 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?