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
Rahul Rana 32Rahul Rana 32 

How to get the data of a particular key of JSON after converting it to Wrapper class.

Hi Salesforce Experts,

I've below JSON : 

{
  "records": [
    {
      "childprods": [
        {
          "grandchilds": [
            {
              "Name": "Apple TV 1"
            },
            {
              "Name": "Apple TV 2"
            }
          ]
        }
      ]
    }
  ]


Now I want to deserialize this JSON and convert it into wrapper, and get the value of key 'Name' whose value is 'Apple TV 2'.

I've used below code to deserialize it and convert it into wrapper: 

public class recordWrapper(){
    public class grandchild(){
        public String Name;
    }
    public class childprod(){
        public List<grandchild> grandchilds;
    }
    public class record(){
        public List<childprod> childprods; 
    }
    public List<record> records;
}

String jsonBody2 = '{"records": [{"childprods": [{"grandchilds":[{"Name": "Apple TV 1"},{"Name": "Apple TV 2"}]}]}]}';

recordWrapper deserializeResults2 = (recordWrapper) JSON.deserialize(jsonBody2, recordWrapper.class);

System.debug('--deserializeResults2--'+deserializeResults2);

Below is the value of deserializeResults2 :
deserializeResults2--recordWrapper:[records=(record:[childprods=(childprod:[grandchilds=(grandchild:[Name=Apple TV 1], grandchild:[Name=Apple TV 2])])])]

Could you please tell me how to get the Name (with value Apple TV 2) through VF as well as apex.

Thanks in advance.
 
MantoManto
Is this Something you are looking for?

public class recordWrapper {
    public class grandchild{
        public String Name;
    }
    public class childprod{
        public string family;
        public List<grandchild> grandchildren;
    }
    public class record{
        public List<childprod> childprods; 
    }
    public List<record> records;
}

String jsonBody2 = '{"records": [{"childprods":  [{"family": "Apple", "grandchildren":[{"Name": "Apple TV 1"},{"Name": "Apple TV 2"}]}]}]}';

recordWrapper deserializeResults2 = (recordWrapper) JSON.deserialize(jsonBody2, recordWrapper.class);

System.debug('--deserializeResults2--'+deserializeResults2);

for(recordWrapper.record rec: deserializeResults2.records){
    system.debug('Rec: '+rec);
    for(recordWrapper.childprod chprd : rec.childprods){
         system.debug('childprod: '+chprd);  
        system.debug('childprod.Family: '+chprd.family);
        for(recordWrapper.grandchild gc : chprd.grandchildren ){
            system.debug('gc: '+gc);  
            system.debug('child Name: '+gc.Name);    
        }
    }
}