function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Anil PandeyAnil Pandey 

Why JSONParser getText() returning NULL

JSONParser parser = JSON.createParser(res.getbody());
        while(parser.nextToken() != null){
        
        if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getCurrentName() == 'originalTeamId')){
               String returnteam = parser.getText();
               }
        
        System.debug(parser.nextToken());
        System.debug(parser.getCurrentToken());
        System.debug(parser.getCurrentName());
        System.debug(parser.getText());
        System.debug(returnteam);
        }        
             
    if(returnteam != null){
        teams[0].OldTeamId__c = returnteam;
    }

Per the documentation (http://www.salesforce.com/us/developer/docs/dbcom_apex230/Content/apex_methods_system_jsonparser.htm), the getText() method "Returns the textual representation of the current token or null if there's no current token. No current token exists, and therefore this method returns null, if nextToken has not been called yet for the first time or if the parser has reached the end of the input stream."

In my debug above, getCurrentToken() returns a value, and nextToken() is called in the while loop. Why is getText() null in the debug?

Please suggest !!!
Hermes Yan 11Hermes Yan 11
I may be wrong but I think you need to parser.nextToken(); before line 5 as your doing getText on the field name.

If you look at the example herehttps://www.salesforce.com/us/developer/docs/apexcode/Content/apex_json_jsonparser.htm after they identify the field they advance one more to get to the actual value.
 
Anil PandeyAnil Pandey
Hi Hermes,

Thank you for giving it a shot. Actually the problem was with the IF loop condition. I have to put VALUE_STRING instead of FIELD_NAME in the IF loop because in JSON, FIELD_NAME was behaving as Key. I got it working through this. I appreciate your effort.