How to deserialize array of JSON objects to an APEX Map

  • I need to parse a JSON string like this into an APEX Map object, where I only want to go through the objects in the "results" array. How can I do this?

    {  
       "count":6176,
       "next":"https://example.herokuapp.com/objects/recaptures/?page=2",
       "previous":null,
       "results":[  
          {  
             "id":"101009",
             "annual_savings":"96613.91",
             "cost":1,
          },
          {  
             "id":"101116",
             "annual_savings":"40851.75",
             "cost":1,
          }, ...
    

    I need to put this into a Map like this:

    public Map<String, String> myMap { get; set; }
    

    I've found a method called JSON.deserialize but how can I get it to just parse the "results" array?

    What do you expect the key and value to be?

  • Charles T

    Charles T Correct answer

    5 years ago

    Edit: I have a year more experience as a developer now and I realize my answer here was a bit too simplistic.

    If you are looking to deserialize untyped without custom classes (so basically assume the data has the right structure at runtime) you can do it but it requires some steps. My original answer looked like this:

    Map<String, Object> meta = (Map<String, Object>) JSON.deserializeUntyped(JsonString);
    List<Map<String, String>> myMaps = (List<Map<String, String>>) meta.get('results');
    

    I don't think that actually works. You basically have to cast one level at a time, like so:

    Map<String, Object> meta = (Map<String, Object>) JSON.deserializeUntyped(JsonString);
    List<Map<String, Object>> myMaps = new List<Map<String, Object>>();
    List<Object> myMapObjects = (List<Object>) meta.get('results');
    for (Object obj : myMapObjects) {
        myMaps.add((Map<String, Object>)obj);
    }
    

    And then if you wanted to end up with a Map<String, String> you'd need to iterate through the Map<String,Object> and cast each value to a String and construct a new Map. It's a bit tiresome but it can be done.

    More info here with example of error catching: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_System_Json.htm#apex_System_Json_deserializeUntyped

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used