Last active
March 27, 2021 23:24
-
-
Save ysfdc/d645f574818e5dad5f7c1bbc7eb24e24 to your computer and use it in GitHub Desktop.
Simple JSON Parser APEX
This file contains 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 parseJson { | |
public static void parseJson() { | |
String jsonString = '{"Hogwarts":[{"Houses":[{"Hufflepuff":{"members":2}},{"Gryffindor":{"members":4}},{"Slytherin":{"members":3}},{"Ravenclaw":{"members":2}}]},{"Common Areas":{"Inside":"The Great Hall","Outside":"Hagrids Hut"}}]}'; | |
// Load JSON and get to the root of the document | |
Map<String, Object> hogwarts = (Map<String,Object>)JSON.deserializeUntyped(jsonString); | |
// "Hogwarts" is a List | |
List<Object> hogwartsResults = (List<Object>)hogwarts.get('Hogwarts'); | |
// Houses is the first element in the "Hogwarts" list | |
Map<String, Object> houses = (Map<String, Object>)hogwartsResults[0]; | |
List<Object> houseResults = (List<Object>)houses.get('Houses'); | |
// "Houses" is a List - let's grab the first one | |
Map<String, Object> individualHouse = (Map<String,Object>)houseResults[0]; | |
//This will print Hufflepuff and it's members | |
system.debug('The best house is: ' + individualHouse); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment