I have JSON something like below and my code is written for an update as well as an insert but if I'm trying to insert another set of records it will only go to update since I iterating only OppMap which is nothing but Opportunity Records. what I want is when I try to insert another set some values match with project id needs to update and the remaining value need to insert in Opportunity
[
{
"OWNER_TYPE":"Government",
"ProjectId":"001"
},
{
"OWNER_TYPE":"Government",
"ProjectId":"002"
}
]
List<object> arr =(List<object>)JSON.deserializeUntyped(response.getBody());
List<Opportunity> opList = new List<Opportunity>();
List<Opportunity> opListUpd = new List<Opportunity>();
Map<String,Object> mp_StrObj = new Map<String,Object>();
Map<String,Object> newMap = new Map<String,Object>();
for(object obj :arr)
{
mp_StrObj = (Map<string,Object>)obj;
newMap.put(string.valueof(mp_StrObj.get('ProjectId')),mp_StrObj);
}
system.debug('val'+newMap);
System.debug('mp_StrObj'+mp_StrObj);
Map<String, Opportunity> OppMap = new Map<String, Opportunity>([SELECT Id,RecordTypeId,Name,CloseDate,StageName,ProjectId FROM Opportunity WHERE ProjectId IN :newMap.keySet()]);
for (String eachIdFromMap : newMap.keyset())
{
System.debug('clsDataMap'+newMap);
System.debug('e'+eachIdFromMap);
System.debug('OppMap'+OppMap);
if(!OppMap.isEmpty()){
for(Opportunity le:OppMap.values())
{
if(!OppMap.isEmpty() && le.ProjectId== eachIdFromMap)
{
System.debug('update');
le.CloseDate=Date.today();
le.RecordTypeId='01228000001HoFFAA0';
le.Name='Testupd'+String.valueof(mp_StrObj.get('PROJECTID'));
le.StageName='S0 - Prospecting';
opListUpd.add(le);
}
else
{
Opportunity Opp = new Opportunity();
Opp.CloseDate=Date.today();
Opp.Name='Test'+String.valueof(mp_StrObj.get('PROJECTID'));
Opp.StageName='S0 - Prospecting';
opList.add(Opp);
}
}
}
if(OppMap.isEmpty())
{
System.debug('insert');
Opportunity Opp = new Opportunity();
Opp.CloseDate=Date.today();
Opp.Name='Test'+String.valueof(mp_StrObj.get('PROJECTID'));
Opp.StageName='S0 - Prospecting';
opList.add(Opp);
}
System.debug('opListUpd'+opListUpd);
System.debug('opList'+opList);
if(opListUpd.size()>0)
{
update opListUpd;
}
if (opList.size()>0){
insert opList;
}