how to parse the JSON object in salesforce

  • how to parse the json string . here multiple contact,multiple postalcode and mulitple contactnumber .how can i get the values from this json output.like list of contacts,list of postalcode and list of contactnumber.

    {
        "CompanyContacts": [
            {
                "contact": "pn0",
                "postalcode": "0",
                "contactnumber": "pc0"
            },
            {
                "contact": "pn1",
                "postalcode": "1",
                "contactnumber": "pc1"
            },
            {
                "contact": "pn2",
                "postalcode": "2",
                "contactnumber": "pc2"
            }
        ]
    }
    
  • pjcarly

    pjcarly Correct answer

    8 years ago

    Take a look at JSON.deserialize(); (documentation)

    In your case, what you will have to do is create 2 inner classes like so:

    public class CompanyContacts
    {
         public List<CompanyContactsWrapper> CompanyContacts;
    }
    
    public class CompanyContactsWrapper
    {
         public String contact;
         public String postalcode;
         public String contactnumber;
    }
    

    then deserialize your JSON string in a new instace of the classes you created.

    CompanyContacts companycontacts = (CompanyContacts)JSON.deserialize(jsonstring, CompanyContacts.class);
    

    now you'll be able to programatically approach the values of your json string in the new list.

    Thanks PJC for your response... i tried what you said i got out put like this from this out put how to get the list,list and list pls help how to solve this problem... output: CompanyContacts: [CompanyContacts=(CompanyContactsWrapper:[postalcode=1, contact=pn1, contactnumber=pc1], CompanyContactsWrapper:[postalcode=, contact=, contactnumber=], CompanyContactsWrapper:[postalcode=, contact=, contactnumber=]) ] Thanks

    you just loop over your list: for(CompanyContactsWrapper wrapper : companycontacts.CompanyContacts){ wrapper.contact; wrapper.postalcode;} then you can do whatever you want with that data, put it in other lists, make contacts, whatever ;)

    Thank you very much for your valuable input to resolve our constrains..Thanks

    @Kittu Good Question

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM