1

I have a JSON response that returns a List which contains city names. I need to de-duplicate this list. Here is my apex:

    global void myLeadsCities(Map<String,Object> inputJsonMap) {
        Set<String> leadCities = new Set<String>();
        List<Object> objs = (List<Object>)inputJsonMap.get('leads');
        for (Object o : objs) {
//console.log(o);  //this returns example: {city=New York} or {city=Boston}, etc...
            //how do I get o.city
            //leadCities.add(o.city);
        }
    }

Apex doesn't recognize personName so it fails. How do I read a value from "ANY" Object type?

1 Answer 1

3

You have to cast to another Map:

for (Object o : objs) {
  Map<String, Object> leadFields = (Map<String, Object>)o;
  String city = (String)leadFields.get('city');
  System.debug(city);
}

Object (ANY) is the parent of all objects, and you can't really "do" anything with it. You need to cast it to a subtype (Boolean, Map, List, String, whatever) to get useful functionality with it.

You can use instanceOf to detect the runtime value of an Object. For JSON.deserializeUntyped, it will always be one of Boolean, String, Integer/Long, Double/Decimal, List<Object>, or Map<String, Object>.

1
  • appreciate the explanation. I wish I could upvote it twice :)
    – user569925
    Commented Mar 9, 2021 at 23:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .