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
MokshadaMokshada 

How to parse JSON data into account and Contact

I have one JSON data as_
[
    {
        "AccountName":"Test Account new",
        "Desc":"Test Desc",
        "Phone":"9898989898",
        "ContactLastName":"Test contact
    }
]
 
I want to create Account and Contact from above json data. How to do that? Can anyone help.

Thanks,


 
Prateek Prasoon 25Prateek Prasoon 25
Sure! In Salesforce, you can parse JSON data using Apex
Here's an example of how you can create an Account and Contact from the JSON data you provided
// Define a wrapper class to hold the JSON data
public class AccountContactWrapper {
    public String AccountName;
    public String Desc;
    public String Phone;
    public String ContactLastName;
}

// Parse the JSON data and create an Account and Contact for each object
String jsonString = '[{"AccountName":"Test Account new","Desc":"Test Desc","Phone":"9898989898","ContactLastName":"Test contact"}]';
List<AccountContactWrapper> accountContactList = (List<AccountContactWrapper>) JSON.deserialize(jsonString, List<AccountContactWrapper>.class);

List<Account> accountList = new List<Account>();
List<Contact> contactList = new List<Contact>();
for (AccountContactWrapper acw : accountContactList) {
    // Create a new Account and populate its fields
    Account account = new Account();
    account.Name = acw.AccountName;
    account.Description = acw.Desc;
    account.Phone = acw.Phone;
    accountList.add(account);

    // Create a new Contact and populate its fields
    Contact contact = new Contact();
    contact.LastName = acw.ContactLastName;
    contact.AccountId = account.Id;
    contactList.add(contact);
}

// Insert the new Account and Contact records
insert accountList;
insert contactList;

If you find this answer helpful, Please mark it as the best answer.
SubratSubrat (Salesforce Developers) 
Hello Mokshada ,

Requesting you to go through this JSON Parsing Help Documentation for your referrence -> https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_jsonparser.htm

Hope it helps too .
Thank you.
MokshadaMokshada
Hi prateek ,
I was trying to run your code but getting error,
User-added image
I have tried copying your code only . I am not getting why it is giving error can you please help?
I have given " " correctly still it is showing missing ". can you please check .


Thanks,