Below apex method helps in finding record corresponding to a key from the JSON.
public static String parserUtility(String jsonString, String recordType){
try{
JSONParser parser = JSON.createParser(jsonString);
while (parser.nextToken() != null) {
if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
parser.nextToken();
if(parser.getCurrentName() == recordType){
return parser.getText();
}
}
}
}catch(Exception e){
e.getMessage();
return null;
}
return '';
}
public static String parserUtility(String jsonString, String recordType){
try{
JSONParser parser = JSON.createParser(jsonString);
while (parser.nextToken() != null) {
if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
parser.nextToken();
if(parser.getCurrentName() == recordType){
return parser.getText();
}
}
}
}catch(Exception e){
e.getMessage();
return null;
}
return '';
}
Example:
String jsonString = '{"size":1,"totalSize":1,"done":true,"queryLocator":null,"entityTypeName":"ApexOrgWideCoverage","records":[{"attributes":{"type":"ApexOrgWideCoverage","url":"/services/data/v39.0/tooling/sobjects/ApexOrgWideCoverage/716dddsdadfef"},"Id":"7134354580efdfsdf","PercentCovered":33}]}';
parserUtility(jsonString, 'PercentCovered');
it returns: 33
Comments
Post a Comment