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
bharath kumar 52bharath kumar 52 

Json generator difference while making callouts

Hi All,

I haven't worked much on integrations so i would like to know what's the difference in these 2 syntaxes below in generating json, i personally feel they do the same thing but i would like to know the differences and any other pros and cons of both the approaches and when to use which approach.

Generating json :
Approach 1
JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartObject();
gen.writeFieldName('Patient satisfaction');
gen.writeStartArray();
for (Patient_Satisfaction__c  patientSatisfaction : PrRecord) {
gen.writeStartObject();
gen.writeObjectField('First name', patientSatisfaction.Reporter_First_Name__c);
gen.writeObjectField('Last name', patientSatisfaction.Reporter_Last_Name__c);
gen.writeObjectField('Phone', patientSatisfaction.Reporter_Phone__c);
gen.writeObjectField('description', patientSatisfaction.Description_of_Feedback__c);gen.writeEndObject();
     } 
gen.writeEndArray();
gen.writeObjectField('incident_group_id',7387);
gen.writeObjectField('Name', 'TestAPI');
gen.writeEndObject();
//// This code snippet generates a json array

Approach2:
String jsonstr='{"Name":"'+ Accname +'","Phone":"'+ phone +'"}';

 Http h2= new Http();
//setting headers and other stuff required for callouts
//
//
req2.setBody(jsonstr);

            HttpResponse res2=h2.send(req2);
            System.debug(res2+'###1213createresp');
            deserializeResponse deresp2=(deserializeResponse)System.JSON.deserialize(res2.getBody(),deserializeResponse.class);



 
Best Answer chosen by bharath kumar 52
Rahul Kumar DeyRahul Kumar Dey
Hi Bharath,

The first approach is basically you generate a json structure using JSONGenerator class you can google it for detailed usage. And in second approach you basically not generating any json structure but you deserialize, whatever comes in response body.
Bonus: You can generate json using wrapper class also and its easy and fastest as compare JSONGenerator.

Don't forgot to mark this as best answer if it's clear you boudt, so it helps other people as well.

Thanks,
Rahul