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
Michael MMichael M 

How to parse JSON with repeated variables- specific question

Hello this is my first time parsing a JSON respnse, so this may be a basic question. In my code, I am making a callout and am receiving a 200 response, and receiving the response JSON. However, at this point I am getting stuck with how to actually parse the JSON. I am familiar with the concepts of wrapper classes and the JSONParse class, but what I am requesting here, if possible, is if someone can actually show me how to parse the response AND save the data into my object's fields.  This would be a tremendous help for me. 

Here is a snippet of the response (if you can show me how to do it with this, I will learn how to do it myself for the rest of it.) I need to map the fields to corresponding fields on my custom object called Eligibility__c. Please note also that in the JSON, there a some repeats (i.e. "service_name" appears multiple times in the "third_party" section. )

Again, the end result needs to be that I create a new eligibility record with each value in the json populating a field on the eligibility object. 


{
"request_id": "1a87457e-f11c-11ea-863c-d20ff8abdbc2",
"request_status": "results_ready",
"result_path": "emed.json.output/PF03367D-2495_2020-09-07_15-09-21_271.json",
"result": {
"first_name": "JOHN",
"last_name": "SMITH",
"id_type": "MI",
"subscriber_id": "123456",
"gender": "M",
"birthdate": "19551220",
"address": {
"info": "123 CENTRAL AVE",
"city": "New York",
"state": "NY",
"zip_code": "10301"
},

"third_party": [
          {
            "service_name": "Health Benefit Plan Coverage",
            "service_type": "30",
            "coverage_level": "IND",
            "info_code_name": "Other or Additional Payor",
            "entity": {
              "name": "BC/BS EMPIRE",
              "id_code": "P4",
              "benefit_id_name": "Payor Identification",
              "benefit_id_qual": "PI",
              "benefit_id": "12",
              "address": {
                "info": "PO BOX 1407 CHURCH ST STATION",
                "info_2": "ATTN  CLAIMS DEPT",
                "city": "NEW YORK",
                "state": "NY",
                "zip_code": "100081407"
              }
],
     {
            "service_name": "Health Benefit Plan Coverage",
            "service_type": "30",
            "coverage_level": "IND",
            "info_code_name": "Other or Additional Payor",
            "entity": {
              "name": "BC/BS EMPIRE - DENTAL",
              "id_code": "P4",
              "benefit_id_name": "Payor Identification",
              "benefit_id_qual": "PI",
              "benefit_id": "12DNT",
              "address": {
                "info": "PO BOX 1407",
                "city": "NEW YORK",
                "state": "NY",
                "zip_code": "100081407"
              }
            }}

 
Best Answer chosen by Michael M
AmitSoniAmitSoni
HI Michael, 

Please use below tools for your requirement:
https://json2apex.herokuapp.com/ (https://www.adminbooster.com/tool/json2apex)
https://www.adminbooster.com/tool/json2apex

This will generate the apex code along with test class.

Hope this will be helpful!! Please mark this as best answer if this works out for you.

All Answers

AmitSoniAmitSoni
HI Michael, 

Please use below tools for your requirement:
https://json2apex.herokuapp.com/ (https://www.adminbooster.com/tool/json2apex)
https://www.adminbooster.com/tool/json2apex

This will generate the apex code along with test class.

Hope this will be helpful!! Please mark this as best answer if this works out for you.
This was selected as the best answer
Michael MMichael M
Hi Amit,

Ok so I see that I can generate some apex. But what do I do with that? How do I fit it in with my current code? And how do I create a new Eligibility__c record from it and map it to the fields? Can you show me a real practical example of all the steps, if possible? To give you a sense, I am working with a trigger on the Lead object. When a Lead is inserted, I make the callout from an apex class. That is what I'm up to, as you can see here... my question is: what is the next steps?

  public object  makePostCallout() {
    Lead ref =[Select Id, firstname, lastname, gender__c, patient_dob__c, patient_ssn__c from Lead where Id = :ApexPages.currentPage().getParameters().get('id')]; 
           system.debug('***NAME OF REFERRAL***: '+ ref.firstname + ' ' + ref.lastname);
    String ssnReplace; 
           if (ref.Patient_SSN__c != null){
            ssnReplace = ref.Patient_SSN__c.replace('-','');
           }
    String genderLetter;
           if (ref.Gender__c == 'Male'){
               genderLetter = 'M';
           } else if (ref.Gender__c == 'Female'){
               genderLetter = 'F';
           }
           
           String first;
           String second;
           String third;
            String d = String.valueOf(ref.Patient_DOB__c);
           system.debug('***dob string raw: ' + d);
                first = d.substring(0,4);
                second = d.substring(5,7);
                third = d.substring(8,10);
           String dob = first + second + third;
           system.debug('***dob formatted: ' + dob);

 string reqbody;
  string reqbodyResp;
     StaticResource r =[Select Id,Body from StaticResource where Name='EMedCalloutBody' limit 1];
      reqBody=r.body.toString();         
       HttpRequest req = new HttpRequest();
           req.setHeader('Content-Type', 'application/json');
                req.setMethod('POST');
                req.setBody(reqBody);
                req.setEndpoint('callout:Emed');
                req.setTimeout(2 * 60 * 1000);
system.debug('ENDPOINT: ' + req.getendpoint());
  //  system.debug('FULL REQUEST: ' + req);
         system.debug('BODY: '+ req.getBody());
         Http http = new Http();
           HttpResponse response = http.send(req);
        if (response.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        } else {
            system.debug(response.getstatuscode());
           System.debug(response.getBody());
             string requestId = response.getbody().substringAfter('"request_id": ').substringBefore(',');
       StaticResource r2 =[Select Id,Body from StaticResource where Name='EmedResponseBody' limit 1];
               reqbodyResp=r2.body.toString();
              reqbodyResp=reqbodyResp.replace('{{requestId}}', requestId);
                  HttpRequest req2 = new HttpRequest();
           req2.setHeader('Content-Type', 'application/json');
                req2.setMethod('POST');
                req2.setBody(reqbodyResp);
                req2.setEndpoint('callout:Emed_Response');
                req2.setTimeout(2 * 60 * 1000);
            system.debug('ENDPOINT2: ' + req2.getendpoint());
            system.debug('BODY2: '+ req2.getBody());
             Http http2 = new Http();
           HttpResponse response2 = http2.send(req2);
        if (response2.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
                response2.getStatusCode() + ' ' + response.getStatus());
        } else {
            system.debug(response2.getstatuscode());
           System.debug(response2.getBody());
        }

        }