Search code examples
salesforceapex

Looping over all members of a class


In apex, if I want to loop over all members of a "inner" class & create a map from it (member name to its value). How do I do that?

Thanks in advance.

public class fromJSON{
  

public boolean success; public Integer timestamp; //1646140623 public String base; //EUR public String dateJ; //2022-03-01 public Map<String, Decimal> rates; public cls_rates rates;

 class cls_rates {
     public Double AED; 
     public Double AFN; 
     public Double ALL; 
     public Double AMD; 
     public Double ANG; 
     public Double AOA; 
     public Double ARS; 
     public Double AUD; 
     public Double AWG; 
     public Double AZN; 
     public Double BAM; 
     public Double BBD; 
     public Double BDT; 
     public Double BGN; 
     public Double BHD; 
     public Double BIF; 
     public Double BMD; 
     public Double BND; 
     public Double BOB; 
     public Double BRL; 
     public Double BSD; 
     public Double BTC; 
     public Double BTN; 
     public Double BWP; 
     public Double BYN; 
     public Double BYR; 
     public Double BZD; 
     public Double CAD; 
     public Double CDF; 
     public Double CHF; 
     public Double CLF; 
}

}


Solution

  • We may need to serialize the inner class object and we would need to deserialize it using deserializeUntyped method for holding the inner class members variables into a map.

    //Create a instance of the inner class
    fromJSON.cls_rates rates=new fromJSON.cls_rates();
    
    //Setting some variable for demo purpose
    rates.AED = 10.0;
    
    //Serializing the inner class instance to json string 
    String jsonStr = JSON.serialize(rates);
    
    
    //Deserializing the json string to a map with key and values from the inner class
    Map<String, Object> jsonMap = (Map<String, Object>)JSON.deserializeUntyped(jsonStr);
    
    System.debug('jsonMap : '+jsonMap);