Created
March 4, 2022 23:08
-
-
Save victorabraham/a60ebd3268182cc96921723ce3de971e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public with sharing class Utils { | |
| //If parser is at start of inner object or array, skipping till end of the section | |
| public static JSONParser skipTillEndOfSection(JSONParser parser) { | |
| if(parser != null && parser.getCurrentToken() == JSONToken.START_ARRAY) { | |
| if(parser.getCurrentToken() == JSONToken.START_ARRAY) { | |
| while(parser.getCurrentToken() != JSONToken.END_ARRAY) { | |
| parser.nextToken(); | |
| if(parser.getCurrentToken() == JSONToken.START_ARRAY || parser.getCurrentToken() == JSONToken.START_OBJECT) { | |
| skipTillEndOfSection(parser); | |
| } | |
| } | |
| }else if(parser.getCurrentToken() == JSONToken.START_OBJECT) { | |
| while(parser.getCurrentToken() != JSONToken.END_OBJECT) { | |
| parser.nextToken(); | |
| if(parser.getCurrentToken() == JSONToken.START_ARRAY || parser.getCurrentToken() == JSONToken.START_OBJECT) { | |
| skipTillEndOfSection(parser); | |
| } | |
| } | |
| } | |
| } | |
| return parser; | |
| } | |
| /************************************************************************************** | |
| * @Description This method extract value of inner attributes in a JSON | |
| * @Param String - JSON string | |
| * @Param String - JSON attribute path | |
| * @Return String - This sample assumes returned value is a string | |
| * @Example | |
| * Utils.extractAttributeFromJson('{"data":{"user":{"organization":{"id":"123"}}}}', 'data.user.organization.id'); | |
| **************************************************************************************/ | |
| public static String extractAttributeFromJson(String jsonResponse, String attrString) { | |
| if(String.isBlank(jsonResponse) || String.isBlank(attrString)) return null; | |
| List<String> attrPath = attrString.split('\\.'); | |
| JSONParser parser = JSON.createParser(jsonResponse); | |
| Integer index = 0; | |
| parser.nextToken(); | |
| while(parser.nextToken() != null) { | |
| if (parser.getCurrentToken() == JSONToken.FIELD_NAME) { | |
| if(attrPath[index] == parser.getText()) { | |
| if(index == attrPath.size()-1) { | |
| parser.nextToken(); | |
| return parser.getText(); | |
| }else if(parser.nextToken() == JSONToken.START_OBJECT) { | |
| index++; | |
| } | |
| } | |
| }else if(parser.getCurrentToken() == JSONToken.START_OBJECT || parser.getCurrentToken() == JSONToken.START_ARRAY) { | |
| skipTillEndOfSection(parser); | |
| } | |
| } | |
| return null; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment