using the JSONParser class i've implemented the following code:
String data = '{"Asset__c": "abc123","Opening_Speed__c": "50", "Closing_Speed__c": "50"}';
JSONParser parser = JSON.createParser(data);
parser.nextToken();
//advance to the next token
while (parser.nextToken() != NULL) {
String fieldName = parser.getCurrentName();
String fieldValue = parser.getText();
System.debug('Current token is: ' + parser.getCurrentToken() +
' and FieldName is: ' + fieldName +
' and FieldValue is: ' + fieldValue);
}
And this returns the following lines in the debug statements.
I can't understand why it's setting the fieldName and the fieldValue variables with the FIELD_NAME the first time through, then setting them as expected (name and value populated correctly) on the second pass…
I've tried adding an IF(parser.getCurrentToken() == 'FIELD_NAME') test in there to separate the setting of fieldName from fieldValue but that throws a type error – cannot compare JSONToken to String… but can't cast that JSONToken to String to do that either..
Obviously, something simple i'm missing here…
Best Answer
JSONToken is a type of Enum. You can't cast an Enum to a String, but you do have two alternatives.
The preferred alternative is to use the literal Enum token:
Otherwise, you could also choose to use
name
to convert an Enum to a String:I would strongly advise that you don't do this, because using an Enum token directly avoids the possibility that you'll make a typo in the string.
Also, keep in mind that the token may be one of several types of values, such as VALUE_NULL or VALUE_NUMBER_FLOAT. See the first link in this answer for the possible values you may encounter while parsing JSON.