I have a custom object where records are in the below structure. enter image description here

I am trying to build parent child structure as below. Where Carrier is the parent and other records treated as child. enter image description here

From the code it is retrieving list properly but for some reasons it is duplicated in the final output. I am wondering what I am doing wrong here as this is not giving expected output.

enter image description here

public static String fetchInsuranceData(String recID, String sObjName) {
    List<Insurance_Accepted__c> accptIns = [SELECT Office__c,FirstName__c, LastName__c, EffectiveDate__c, Carrier__c, IsHMO__c, IsPPO__c
                                            FROM Insurance_Accepted__c WHERE Office__c = :recID AND Carrier__c='ADVANTICA PPO' AND EpicProvider__r.Is_Active__c=TRUE ORDER By Carrier__c];

    InsAcptWrapper insWrap = new InsAcptWrapper();
    InsProviderWrapper insProvWrap = new InsProviderWrapper();
    for(Insurance_Accepted__c ar: accptIns){            
      insWrap.carrierName= (String)ar.get('Carrier__c');
      insProvWrap.fName = (String)ar.get('FirstName__c');      
      insProvWrap.lName = (String)ar.get('LastName__c');
      insProvWrap.hmo = (Boolean)ar.get('IsHMO__c');
      insProvWrap.ppo = (Boolean)ar.get('IsPPO__c');
      insProvWrap.effectiveDate = (Date)ar.get('EffectiveDate__c');
      insWrap.provItems = carrierMap.get(insWrap.carrierName);
      if(insWrap.provItems == null){
        insWrap.provItems = new List<InsProviderWrapper>();        
      carrierMap.put(insWrap.carrierName, insWrap.provItems);      
     return JSON.serializePretty(carrierMap);    
  // wrapper class
  public class InsAcptWrapper {     
    public String carrierName{get;set;}    
    public List<InsProviderWrapper> provItems{get;set;}
    public class InsProviderWrapper{      
      public String fName{get;set;}
      public String lName{get;set;}
      public Boolean hmo{get;set;}
      public Boolean ppo{get;set;}
      public Date effectiveDate{get;set;}

1 Answer 1


You are defining insProvWrap outside of the for loop. Then adding it to the list of items. In the next round of the loop, you are updating the fields on insProvWrap but since that is still the same variable, the record that is already in the list is also updated (basically you are adding the exact same record to the list 2 times).

Very nice article about that here by Josh Kaplan: https://developer.salesforce.com/blogs/developer-relations/2012/05/passing-parameters-by-reference-and-by-value-in-apex

The solution is to move the definition of insProvWrap inside the for loop. And probably insWrap is better off there as well once you need to handle multiple carriers in 1 dataset.

  • Calirbois: Apologies on getting late to this. Thanks for the pointer and it worked.
    – user28452
    Nov 10, 2022 at 11:44

You must log in to answer this question.

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