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
Mathías del Valle SanchezMathías del Valle Sanchez 

How to serialize an object as JSON?

Hi,

I got a problem, i need to convert the "Case" Object into a Json and after convert that Json in a Object

I know that i have to use JSON.serialize and JSON.deserialize. but i don't how.
SwethaSwetha (Salesforce Developers) 
HI Mathías ,
The example provided in https://www.infallibletechie.com/2017/09/how-to-convert-sobject-to-json-string.html is in the context of Contact object but should help you get started.
 
Contact con = new Contact(FirstName = 'First', LastName = 'Last', Phone = '9999999999', Email = 'Test@test.com');
/* 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);

Also see https://salesforce.stackexchange.com/questions/101885/parse-json-string-to-object

If this information helps, please mark the answer as best. Thank you
Test Dev 81Test Dev 81
Case c = new case();
c.Subject = 'case subject';
c.description = 'test description';
//add more data into fields as you want
        String jsonStr = Json.serialize(c);

System.debug(jsonStr);

Case c2 = (Case) Json.deserialize(jsonStr , Case.class);
System.debug(c2);

 
CharuDuttCharuDutt
Hii Mathías del Valle Sanchez
Try The Below Code
Account Acc = new Account();
Acc.Name = 'Test Acc';
Acc.description = 'test description';

        String jsonString = Json.serialize(Acc);

System.debug(jsonString);

Account Acc2 = (Account) Json.deserialize(jsonString , Account.class);
System.debug(Acc2);
Please Mark it As Best Answer If it Helps
Thank You!

 
Suraj Tripathi 47Suraj Tripathi 47
Hi 
Hi Mathías ,
If you have to convert object into JSON format then you need to use JSON.serialize.

Case c1= new Case();
c1.Subject = 'case subject';
String jsonStr = JSON.serialize(c1);

And if have to have to convert JSON format into Object then you need to use JSON.deserialize.
Case c2 = (Case) JSON.deserialize(jsonStr , Case.class);
 
Please Mark it as Best Answer, if it helps!
Thanks