[SalesForce] 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"
        }
    ]
}

Best Answer

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.