[SalesForce] Process JSON Array

Can someone tell me how to process JSON Array in an Apex REST resource class ?.

My input to the HTTP post method will be like as follows.

[  
   {  
      "Name":"1 A"
   },
   {  
      "Name":"1 B"
   }
]

I did some study on this and found out that I need to utilize JSON Deserialize as follows.

public class CompanyDeserialize {
    public String Name;
    List < CompanyDeserialize > complist = (List < CompanyDeserialize > ) JSON.deserialize(jsonstring, CompanyDeserialize.class);
    System.debug('~~~~ complist :' + complist);
    List < Account > alist = new List < Account > ();

    for (Account a: complist) {
        alist.add(new Account(Name = a.Name));
    }
    System.debug('~~~~ alist :' + alist);
    insert alist;
}

Can someone tell me how to incorporate the above JSON deserializing code snippet into the webservice class below as I am not sure how to pass the JSON array as parameter to this createAccounts() method ?

 @RestResource(urlMapping = '/Account/*')
 global class AccountWS {
    @HttpPost
    global static void createAccounts() {
    }
 }

Best Answer

You can Deserialize the Json Array to a list of accounts like this List<Account> accountsDeserialized = (List<Account>) JSON.deserializeStrict(jSONRequestBody, List<Account>.class); Please find the below example tried with a JSON Array. I used Workbench for testing.

Apex class

@RestResource(urlMapping='/v1/accounts/*') 
global with sharing class AccountWS {
    @HttpPost 
    global static void doPost(){
        RestRequest request = RestContext.request;
        RestResponse response = RestContext.response;
        String jSONRequestBody=request.requestBody.toString().trim();
        List<Account> accountsDeserialized = (List<Account>) JSON.deserializeStrict(jSONRequestBody, List<Account>.class);
        insert accountsDeserialized;
    }
}

JSON Array

[  
   {  
      "Name":"1A",
      "Phone":"5555555555"
   },
   {  
      "Name":"1B",
      "Phone":"4444444444"
   }
]

Workbench enter image description here

Related Topic