Skip to content

Instantly share code, notes, and snippets.

@ysfdc
Last active March 27, 2021 23:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ysfdc/d645f574818e5dad5f7c1bbc7eb24e24 to your computer and use it in GitHub Desktop.
Save ysfdc/d645f574818e5dad5f7c1bbc7eb24e24 to your computer and use it in GitHub Desktop.
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