How to convert sObject to JSON String and JSON string to sObject using apex in Salesforce?

How to convert sObject to JSON String and JSON string to sObject using apex in Salesforce?

JSON.serialize() can be used to convert sObject to JSON String in Salesforce using Apex.

JSON.deserialize() can be used to convert JSON String to sObject in Salesforce using Apex.

Sample Code:

Contact con = new Contact(
	FirstName = 'First', 
	LastName = 'Last', 
	Phone = '9999999999', 
	Email = '[email protected]'
);
/* Code to convert Contact to JSON string */
String strJSON = JSON.serialize(
	con
);
System.debug(
	'JSON String is ' + 
	strJSON
);
/* Code to convert JSON string to Contact */
Contact con1 = ( Contact ) JSON.deserialize(
	strJSON, Contact.Class
);
System.debug(
	'Contact is ' + 
	con1
);

Output:

Leave a Reply