Sunday, November 21, 2021

JSON Class and deserializeUntyped(jsonString)

 


{

  "event": {

    "recorddata": {

      "state": "Success",

      "recordItem": [

        {

          "id": "1",

          "name": "testRecord1"

        },

        {

          "id": "2",

          "name": "testRecord2"

        }

      ]

    }

  }

}


In webservice class,


@RestResource(urlMapping='/postrecorddata/*')

   global with sharing class postrecorddata {

       @HttpPost

      global static responseWrapper postrecorddatamethod(){

        RestRequest req = RestContext.request;

        RestResponse res = Restcontext.response;

        Map<String,Object> map = (Map<String,Object>) JSON.deserializeUntyped(req.requestBody.toString());

        Map<String,Object> map1= (Map<String,Object>) map.get('event');

        Map<String,Object> map2= (Map<String,Object>) map1.get('recorddata');

        String stateValue = (String) map2.get('state');

        List<Object> recordItemList= (List<Object> ) map2.get('recordItem');

        // Perform Some operations and return response

        responseWrapper obj=new responseWrapper();

        obj.message='Data Posted successfully';

        obj.statusCode = '200';

        // Overriding RestResponse object value

        res.statusCode = '200';

        return obj;

        global class responseWrapper{

        global string message;

        global integer statusCode;

        }

        

      }

   }

How to deserializes respone in Apex using deserialize(jsonString, apexType)?

 {

 {

  "nameofsystem": "ExternalSystem1",

  "event": {

    "recorddata": {

      "state": "Success",

      "recordItem": [

        {

          "id": "1",

          "name": "testRecord1"

        },

        {

          "id": "2",

          "name": "testRecord2"

        }

      ]

    }

  }

}

In webservice class,


@RestResource(urlMapping='/postrecorddata/*')

   global with sharing class postrecorddata {

       @HttpPost

      global static returnResponseWrapper postrecorddatamethod(){

        RestRequest req = RestContext.request;

        RestResponse res = Restcontext.response;

        responeWrapper wrapObj= (responeWrapper)                                            JSON.deserialize(req.requestbody.toString(),responeWrapper.class);

        // To get the the state from JSON response.

        String stateInResponse = wrapObj.event.recorddata.state;

        // Perform operations

       returnResponseWrapper obj=new returnResponseWrapper();

        obj.message='Data Posted successfully';

        obj.statusCode = '200';

        // Overriding RestResponse object value

        res.statusCode = '200';

        return obj;

        

      }

 

// Wrapper class for handling request

global class responeWrapper{

 global string nameofsystem;

 global eventData event;

 

}

global class eventData{

 global recorddataObj recorddata;

}

 

global class recorddataObj{

 global string state;

 global recordItemClass[] recordItem;

  

}

 

global class recordItemClass{

 global string id; 

 global string name;

}

// Wrapper class for handling request

 

// Wrapper class for response

      global class returnResponseWrapper{

        global string message;

        global integer statusCode;

        }

 

// Wrapper class for responde

 

}

Export CSV File data by using Apex Code

 List<company__c> extractcompanyMemList = new List<company__c>();

List<company__c> companytList = [select id,name,(select id from companymemebers__r) from company__c];

for(RequestClaimJunction__c company: companytList){
	List<companymemeber__c> companyMemList = company.companymemebers__r;
	if(companyMemList.size() == 0) {
		extractcompanyMemList.add(company);
	}
}

String generatedCSVFile ='';
List<String> queryFields = new List<String>{'Id','Partner Account','Status'};
String fileRow = '';

for(company__c company: extractcompanyMemList){
	fileRow = '';
	fileRow = fileRow +','+ company.Id;
	fileRow = fileRow +','+ company.Name;
	fileRow = fileRow.replaceFirst(',','');
	generatedCSVFile = generatedCSVFile + fileRow + '\n';
}

Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
Blob csvBlob = blob.valueOf(generatedCSVFile);
String csvName = 'company details which doesn't have members.csv';
csvAttachment.setFileName(csvName);
csvAttachment.setBody(csvBlob);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{'Your Email Id'};
String subject = 'company details which doesn't have members CSV';
email.setSubject(subject);
email.setToAddresses(toAddresses);
email.setPlainTextBody('company details which doesn't have members CSV');
email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});

Find Second Largest number from List of Integers

 list<Integer> integerList =new list<Integer>{7, 21, 45, 6,34,56,78,26,65,87,95};

// DESCENDING ORDER

for(Integer i = 0 ; i < integerList.size() ; i ++) {

for(integer j = i+1 ; j <= integerList.size() -1 ; j ++ ){

  integer x = 0 ;

  if(integerList[i] <  integerList[j]){

   x = integerList[i]  ;

   integerList[i] = integerList[j]  ;

   integerList[j]  = x;

  }

}  

}

system.debug(integerList) ;

system.debug('Ssize: '+integerList[1]);

Parent Status Update when all child's status updated to inactive

 public static void updateAccountB2BStatus(List<Contact> lstNewContacts){

    

        map<id,Account> mapUpdateAcc = new map<id,Account>();

        set<id> accIds = new set<id>();

        for(contact con : lstNewContacts){

            if(con.AccountId != null)

                accIds.add(con.accountid); 

        }

        Id CommercialPartnerId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Commercial Partner').getRecordTypeId();

            

        Id OutletId  = [SELECT Id, SobjectType, Name, DeveloperName FROM RecordType WHERE SobjectType='Account'

                        and DeveloperName='Retail_Account' LIMIT 1].Id;

       

        for(account acc : [Select Id,B2B_Status__c,(Select id,ivybat__B2B_Portal_User_Status__c,accountid from Contacts

                                                    where (ivybat__B2B_Portal_User_Status__c ='Active' OR ivybat__B2B_Portal_User_Status__c='Pending Deactivation')) from Account 

                           where id IN: accIds and (RecordTypeID =: CommercialPartnerId OR RecordTypeID =: OutletId)]){

                               if(acc.contacts.size()>0 && acc.B2B_Status__c != 'Active'){

                                   acc.B2B_Status__c = 'Active';

                                   mapUpdateAcc.put(acc.id,acc);

                               } else if(acc.contacts.size() == 0 && (acc.B2B_Status__c == 'Active' || acc.B2B_Status__c == null)){

                                   acc.B2B_Status__c = 'Inactive';

                                   mapUpdateAcc.put(acc.id,acc);

                               }

                           }

        if(mapUpdateAcc.size()>0){

            update mapUpdateAcc.values();

        }

    }