function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
pooja kasliwalpooja kasliwal 

Save dynamic values using json

There are dynamic values in my visualforce page and I want to save those values in object using json. But the dynamic value are getting store in a variable and I am unable to pass variable in json string .how can I achieve it please suggest me.
  Thanks in advance
pconpcon
Can you please provide a small snippet of what you currently have and what you are unable to do.

NOTE: When adding code, please use the "Add a code sample" button (icon <>) to increase readability and make it easier to reference.
pooja kasliwalpooja kasliwal
Hey I am adding the class code. From which I need to save the value of source object, source field , target object , target field using json. I have tried but getting some exception while I am pressing + button .
/*------------------------------------------------ Controller For mapping of fields dynamically ------------------------------------*/
public class Mapper {
     private List<ObjectWrapper> ObjectWrapper;
     public void parseJSONData(){
        ObjectWrapper= new ParseMultipleJsonData().parse();
    }
    public List<ObjectWrapper> getCountries(){
        return ObjectWrapper;
    }

     public String target_object { get; set; }
     public String sourcefield { get; set; }
     public String sourceobject { get; set; }
     public Integer counter=0;
     public Integer index{get;set;}
     public string targetobject{get;set;}
     public string targetfield{ get; set; }
     boolean buttonDisable;
     public String tstr{get;set;}
     public String sstr{get;set;}
     public boolean errordisplay= true;
   
   
/*--------------------------------------------- Method For getting source object using object schema -------------------------------------*/   
    public selectoption[] getsource_objects()
        {
            selectoption[] source_objects = new selectoption[0];
            //Taking token of each source sobject 
            for (Schema.SObjectType obj: Schema.getGlobalDescribe().values()) 
                {
                    // for each token of sobject get name of their sobject and assign it to a variable name 
                    String name = obj.getDescribe().getName();
                    //Excluding system objects and irrelavent objects and add it to the source object picklist
                    if (!obj.getDescribe().isCustomSetting() && obj.getDescribe().getRecordTypeInfos().size() > 0 && obj.getDescribe().isCreateable() &&!name.containsignorecase('history') && !name.containsignorecase('tag') && !name.containsignorecase('share') && !name.containsignorecase('feed')&& !name.containsignorecase('Announcement')&& !name.containsignorecase('CampaignMember')&& !name.containsignorecase('GroupRecord')&& !name.containsignorecase('ContentVersion')&& !name.containsignorecase('Macro')&& !name.containsignorecase('search'))
                    {
                        source_objects.add(new SelectOption(obj.getDescribe().getName(), obj.getDescribe().getLabel()));
                       
                    }
                }
                 source_objects.sort();
                 return source_objects;
                 
        }

/*--------------------------------------------- Method For getting target objects ----------------------------------------------------*/
    public selectoption[] gettarget_objects()
        {
            selectoption[] target_objects = new selectoption[0];
            //Taking token of each target sobject
            for (Schema.SObjectType obj: Schema.getGlobalDescribe().values()) 
                {
                    // for each token of sobject get name of their sobject and assign it to a variable name 
                    String name = obj.getDescribe().getName();
                    //Excluding system objects and irrelavent objects and add it to the target object picklist
                    if (!obj.getDescribe().isCustomSetting() && obj.getDescribe().getRecordTypeInfos().size() > 0 && obj.getDescribe().isCreateable() &&!name.containsignorecase('history') && !name.containsignorecase('tag') && !name.containsignorecase('share') && !name.containsignorecase('feed')&& !name.containsignorecase('Announcement')&& !name.containsignorecase('CampaignMember')&& !name.containsignorecase('GroupRecord')&& !name.containsignorecase('ContentVersion')&& !name.containsignorecase('Macro')&& !name.containsignorecase('search'))
                    {
                        target_objects.add(new SelectOption(obj.getDescribe().getName(), obj.getDescribe().getLabel()));
                    }
                }
                 target_objects.sort();
                 return target_objects;
        }
   
/*--------------------------------------------- Method For getting related child_source_objects.fieldname ----------------------------------------------------*/
public selectoption[] getchild_source_Objects() 
    {
         selectoption[] child_source_Objects = new selectoption[0];
         // if source object is ''--None--' or it is null then source field picklist should add only '--None--'
         if(sourceobject == '--None--' || sourceobject == null )
         {
              child_source_Objects.add(new selectoption('--None--','--None--'));
             
         }
         else
         {
               map<string,string> childObjectsMap = new map<string,string>();
               // the map of all sobjects
               map<string,schema.sobjecttype> describe = schema.getglobaldescribe(); 
               // list of all  related sobjects  and add it to the list
               LIST<Schema.childRelationship> childobject = describe.get(sourceobject).getdescribe().getchildRelationships(); 
               // get the name from the above list 
               for(Schema.childRelationship relobject : childObject)
                {
                     childObjectsMap.put(relobject.getChildSObject().getDescribe().getName(),relobject.getChildSObject().getDescribe().getLabel());
                }
                //get the set of key for each sobject
                for(string objectname :childObjectsMap.keyset())
                {
                    //exclude system objects
                    if(!objectname.containsignorecase('history') && !objectname.containsignorecase('tag') && !objectname.containsignorecase('share') && !objectname.containsignorecase('feed'))
                    {  
                    // skip fields that are not part of the object
                       if(describe.containskey(objectname)) 
                         {    
                              // get the map of all the fields
                              map<string,schema.sobjectfield> fieldmap = describe.get(objectname).getdescribe().fields.getmap(); 
                              //get name of each field and add objectname.fieldname to the source field picklist 
                              for(string fieldname:fieldmap.keyset())
                              {
                                  child_source_Objects.add(new selectoption(objectname+'.'+fieldname,objectname+'.'+fieldname));
                              }
                         }
                    }
                }
         }
         return child_source_Objects;
    } 
    

/*--------------------------------------------- Method For getting related child_target_objects.fieldname ----------------------------------------------------*/
public selectoption[] getchild_target_Objects() 
    {
         selectoption[] child_target_Objects = new selectoption[0];
         // if target object is'--None--' or it is null then target field picklist should add only '--None--'
         if(targetobject== '--None--' || targetobject== null )
         {
              child_target_Objects.add(new selectoption('--None--','--None--'));
         }
         else
         {
               map<string,string> childObjectsMap = new map<string,string>();
               // the map of all sobjects
               map<string,schema.sobjecttype> describe = schema.getglobaldescribe(); 
               // list of all  related sobjects  and add it to the list
               LIST<Schema.childRelationship> childobject = describe.get(targetobject).getdescribe().getchildRelationships();
               // gives the map of all sobjects name and add it to the list
               for(Schema.childRelationship relobject : childObject)
                {
                     childObjectsMap.put(relobject.getChildSObject().getDescribe().getName(),relobject.getChildSObject().getDescribe().getLabel());
                }
                //get the set of key for each sobject
                for(string objectname :childObjectsMap.keyset())
                {
                    //exclude system objects
                    if(!objectname.containsignorecase('history') && !objectname.containsignorecase('tag') && !objectname.containsignorecase('share') && !objectname.containsignorecase('feed'))
                    {
              
                         if(describe.containskey(objectname)) 
                         {
                              // get the map of all the fields
                              map<string,schema.sobjectfield> fieldmap = describe.get(objectname).getdescribe().fields.getmap(); 
                              //get name of each field and add objectname.fieldname to the target field picklist 
                              for(string fieldname:fieldmap.keyset())
                              {
                                  child_target_Objects.add(new selectoption(objectname+'.'+fieldname,objectname+'.'+fieldname));
                              }
                         }
                    }
                }
         }
         return child_target_Objects;
    } 

    /*------------------------------Set Target Object field selected from custompicklist -----------------------------------------------*/
    public pageReference AddRecord()
    {
        ObjectWrapper objwrapper= new ObjectWrapper();
        objwrapper.source_object=sourceobject; 
        objwrapper.source_field= sourcefield;
        objwrapper.target_object= targetobject;
        objwrapper.target_field= targetfield;
        objwrapper.index_number = counter++;
        objectwrapperlist.add(objwrapper);
        return null;
        }

/*------------------------------------------------ Method For displaying error message ----------------------------------------------------*/             
    public PageReference error() 
    {   //split target field and source field and retrive the field name after '.(dot)'
        String[] tparts=targetfield.split('\\.');
        String[] sparts=sourcefield.split('\\.');
        //get the part after '.' and store in variables
        String targetfieldpart= tparts[1];
        String sourcefieldpart= sparts[1];
        //get datatype using getFieldType() method
        Schema.DisplayType tstr=getFieldType(targetfieldpart,targetobject);
        Schema.DisplayType sstr=getFieldType(sourcefieldpart,sourceobject);
        //validation checking and display error message on aprticular condition
        if(tstr != schema.Displaytype.string)
        {
            if(tstr != sstr)
            {
                errordisplay = true; 
                ApexPages.Message  errormessage = new ApexPages.Message(ApexPages.Severity.ERROR,'Both type should be match');
                ApexPages.addMessage(errormessage);
            }
        }
        else
        {
            errordisplay = false; 
        } 
        if(tstr != sstr)
        {
            if(tstr != schema.Displaytype.string)
            {
                errordisplay = true;
                ApexPages.Message errormessages= new ApexPages.Message(ApexPages.Severity.ERROR,'Both type should be match');
                ApexPages.addMessage(errormessages);
             
            }
                     
        }  
        else
        {
            errordisplay = false;
        }           
        system.debug(errordisplay);
        return null;
    }
   
    /*--------------------------------------------- Method For Enable and disable '+' button ----------------------------------------------------*/
    public boolean getbuttonDisable()
    {
        
         if((sourceobject != null && sourceobject != '--None--') && (sourcefield != null && sourcefield != '--None--')&&(targetobject != null && targetobject != '--None--')&&(targetfield != null && targetfield != '--None--'))
         {  
             buttonDisable = false;//button enable
         }
         if(!errordisplay)
         {
             buttonDisable = false;//button enable
         }
         
         if(errordisplay)
         {
             buttonDisable = true;//button dissable
         }
        return buttonDisable;
   }
    
    /*------------------------------------------------ Method to get the datatype of field ----------------------------------------------------*/
    public static Schema.DisplayType getFieldType(String fieldName,String sobjectname)
    {
        Schema.SObjectType t = Schema.getGlobalDescribe().get(sObjectName);
        Schema.DescribeSObjectResult r = t.getDescribe();
        Schema.DescribeFieldResult f = r.fields.getMap().get(fieldname).getDescribe();
        Schema.DisplayType type = f.getType();
        return type;
    }
    //List of object wrapper
    public list<ObjectWrapper> objectwrapperlist{get;set;} 
    // Constructor of the classs 
    public Mapper()
    {
          this.objectwrapperlist= new list<ObjectWrapper>();  
          ObjectWrapper objwrapper = new ObjectWrapper();
    } 
    //Wrapper class
    public class ObjectWrapper
    {
          public string source_object{ get;set;}
          public string source_field{get;set;}
          public string target_object{get;set;}
          public string target_field{get;set;}
          public integer index_number{get;set;}
    }
    
/*---------------------------------------- This method is to remove the rows using index number -----------------------------------------------------------*/
    public PageReference removeRecords()
    {
          for(Integer i=0;i<objectwrapperlist.size();i++)
          {
                if(objectwrapperlist[i].index_number== index)//1 == 1
                {
                      objectwrapperlist.remove(i);
                }
          }
          counter--;
          return null;
    } 
    public class ParseMultipleJsonData {
    
        public List<ObjectWrapper> parse() {
        Mapper mp = new Mapper();
        String sobj = mp.sourceobject;
        String sfld = mp.sourcefield;
        String tobj = mp.targetobject;
        String tfld = mp.targetfield;
        //Integer cont = 'counter';
   
       String jsonMessage = '[{'+
        '  \"source_object\": \"'+sobj+'\",'+
        '  \"source_field\": \"'+sfld+'\",'+
        '  \"target_object\": \"'+tobj+'\"'+
        '  \"target_field\": \"'+tfld+'\"'+
         '}]';
        
        return (List<ObjectWrapper>) System.JSON.deserialize(jsonMessage, List<ObjectWrapper>.class);
    }
    }
}