Skip to content

Instantly share code, notes, and snippets.

@ysfdc
Last active Mar 27, 2021
Embed
What would you like to do?
Simple JSON Parser APEX
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