You need to sign in to do that
Don't have an account?
Meena25
JSON replace formatted text
This is my JSON body which am posting to backend.
{"attributes":{"type":"Lead","url":"/services/data/v46.0/sobjects/Lead/00Q6C00000MWXCgUAP"},"LastName":"rf","FirstName":"wq","Id":"00Q6C00000MWXCgUAP","RecordTypeId":"0121U000000jV0pQAE"}
I just need to replace Id with LeadId while posting as my backend expects that. How can i replace that JSON body text?
This is my code:
Lead lead=[select LastName,FirstName from Lead LIMIT 1];
system.debug('serialized JSON'+JSON.serialize(lead));
body = JSON.serialize(lead);
request.setBody(body);
You need to create a wrapper class for this requirement.
Try the following code to fulfill your requirement:
public class WrapperForChangeJSON {
public static void createNewJSON()
{
Lead lead=[select LastName,FirstName from Lead LIMIT 1];
system.debug('serialized JSON'+JSON.serialize(lead));
String body = JSON.serialize(lead);
Map<String, Object> meta = (Map<String, Object>) JSON.deserializeUntyped(body);
system.debug('----' + meta);
AccountWrapper aObj = new AccountWrapper();
aObj.attributes = meta.get('attributes');
aObj.LastName = meta.get('LastName');
aObj.LeadId = meta.get('Id');
String newJSON = JSON.serialize(aObj);
system.debug('----' + newJSON);
}
public class AccountWrapper {
public Object attributes {
get;set;
}
public Object LastName {
get;set;
}
public Object LeadId {
get;set;
}
}
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi