How do I parse a JSON map into an Apex Map?

  • I am trying to parse the following JSON format into a Object.

    {
      "info1": "blah blah",
      "info2": "blah blah2",
      "info3": 1391673663,
      "info4": "blah4",
      "info5": {
        "AAA": 0.1,
        "BBB": 0.3,
    .....
      }
    }
    

    But the problem is under [info5] list, name like "AAA", "BBB" and their related values are dynamic and always changing.

    How should I make my Object to satisfy this kind of structure? I want to put those values into a Map if possible.

    So that I can easily get "AAA" and its Related values.

    Any input will be so helpful for me.

  • You will have to use JSON.deserializeUntyped method that will deserializes a JSON representation of an appliance object into a map that contains primitive data types and further collections of primitive types. Something like below should work:

    Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(jsonInput);
    Map<String, Object> m2 = (Map<String, Object>) m.get('info5');
    List<decimal> d = new List<decimal>();
    
    for(String s:m2.keyset()) {
        decimal t = (decimal) m2.get(s);
        d.add(t);
    }
    

License under CC-BY-SA with attribution


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

Tags used