I have been developing an Apex Trigger where I build a json string from an incomming Event.
What I do is serialize the event into the json at first, then deserialize it as a Map and add to it some new entries. Finally I serialize the Map into a String and store it within a field named 'Json__c' of a custom object 'Queue__c' and insert it into the DB. The problems are coming when I find that the final value inserted is the first json that I serialize at first, when it should be the last one!
I attach you a summary of my code so that you can better understand what I'm doing:
Queue__c queue = new Queue__c();
String serializedJson = JSON.serialize(event);
Map<String, Object> jsonAsMap = (Map<String, Object>) JSON.deserializeUntyped(serializedJson);
// The variable ownerId is coming with its correct value
jsonAsMap.put('Owner.Id', ownerId);
queue.Json__c = JSON.serialize(jsonAsMap);
Database.SaveResult[] srList = Database.insert(queue);
Within those lines of code, I have written a System.debug() above the INSERT and it gives me the right value of queue.Json__c. However, when I check the value of the new record in the DB I see that queue.Json__c is equal to the 'serializedJson' variable that appears in my code instead of being equal to the last JSON.serialize output.
It is like the insert is forgetting about the changes that I put into 'jsonAsMap' variable, but I cannot understand how that is possible. There is also nothing wrong in the SaveResult list. Why is this happening? Am I missing any concept?
Best Answer
The reason I asked to see all of the code is because sometimes when working with large sets of code, passing variables in and out of methods can have unexpected side effects. Is it possible you are having an issue with passing variables into and back out of methods? Apex uses pass by value for primitive data types (such as a Map or String). If at any point you set
jsonAsMap = <something>
you could be running into this issue. Here is a perfect example from the reference: